Daniel Peñalba
Daniel Peñalba

Reputation: 31847

How do I encode a complete URL string in ASP MVC

I get a url string and would like to transform it to a legal http url:

For example:

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

However, HttpUtility.UrlEncode does not help, as it encodes the entire string (including the legal "://").

Upvotes: 5

Views: 3759

Answers (2)

Carvellis
Carvellis

Reputation: 4042

How about splitting and rejoining:

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());

Upvotes: 0

Bala R
Bala R

Reputation: 108937

See if this 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"

Upvotes: 4

Related Questions