How to encode a complete URL string in ASP MVC

I get the url string and would like to convert it to the legal http URL:

For instance:

"http://one/two/three%four/five#five?six seven" should turn into "http://one/two/three%25four/five%23five?six%20seven"

However, it HttpUtility.UrlEncodedoes not help, since it encodes the entire string (including legal "://").

Thanks in advance

+5
source share
2 answers

See what you want?

   Uri uri = new Uri("http://one/two/three%four/#five?six seven");
   string url = uri.AbsoluteUri + uri.Fragment; 
   // url will be "http://one/two/three%25four/#five?six%20seven#five?six%20seven"
+4
source

How about splitting and repeating:

string url = "http://one/two/three%four/#five?six seven";
string encodedUrl = "http://" + string.Join("/", url.Substring(7).Split('/').Select(part => HttpUtility.UrlEncode(part)).ToArray());
0
source

All Articles