Uri.EscapeDataString() is converting / to %2F

Viewed 44

I am trying to convert strings to URI format, in order to use them in URLs that show some images in my page. I am using ASP.NET Core.

for this I have used System.Web.HttpUtility.UrlEncode() I also tried Uri.EscapeDataString() .

Both methods return practically the same thing (I would not discuss the difference between them in this thread) , but my problem is that the methods are also converting the character "/" to "%2f" .

Here is a piece of code that I am using for that conversion :

        public string StringConvert()
    {
        string decoded= "Example/of/string"  ;
        string toShow = System.Web.HttpUtility.UrlEncode(encoded);   /*Uri.EscapeDataString(encoded); can also be used*/
        return toShow;
    }

I am calling the StringConvert method directly from the HTML view, and use it directly for the src of an img . the image cannot be accessed because of the "%2f" in the address. Might there be a way/workaround to bypass that ?

1 Answers

Converting strings into URIs could be achieved with new Uri(string). However, if you need validation first to make sure it won't blow up with a bad string then you can check out Uri.TryCreate(string, UriKind, out Uri).

Last param would be your URI object or just the result from URI initialization from the first example.

Uri.TryCreate MS docs

Related