[ACCEPTED]-How do I encode an URL?-asp.net

Accepted answer
Score: 36

If your encoding parts of the path:


If your 1 encoding 'arguments':

String.Format( "http://something/?test={0}", System.Uri.EscapeDataString("c#") );
Score: 8

try this

  • in ASP.NET
  • in WinForms using System.Web.dll 1

Score: 3

Url encoding is used to ensure that special 29 symbols included in a url (most likely in 28 a querystring) are not mistakenly interpreted 27 as those used in the parsing and processing 26 of a url. For example, the + symbol is 25 used to indicate a space in a url. However, if 24 you were intending for a + symbol to be 23 a part of your querystring then you would 22 want to encode that querystring before sending 21 it to a browser.

For example. Imagine you 20 have written a page that receives a math 19 equation on the querystring and displays 18 that equation on the page.

The url might 17 be: http://yoursite.com/displayMath.aspx?equation=3+5

The + symbol in this case is intended 16 to be a meaningful part of the equation. However, without 15 a UrlEncode it would be interpreted as representing 14 a space. Reading this value from the querystring 13 on the receiving page would yield "3 5", which 12 is not what was intended.

Instead of redirecting 11 to that url directly, you would want to 10 URL encode the request first. You might 9 write the following code:

string equation = "3+5";
string url = String.Format(@"http://yoursite.com/displayMath.aspx?equation={0}", equation);
string encodedUrl = Server.UrlEncode(url);

This would ensure 8 that a subsequent Request.Querystring["equation"] would receive the equation 7 intact because any special symbols would 6 first be encoded.

I'm not sure I understand 5 your use case for encoding urls. If you 4 could perhaps provide more information on 3 what you are trying to achieve I will attempt 2 to answer more fully. For now I hope that 1 this information is useful.

Score: 0

say you want to create a link with some 3 parameters you can use it as follows:


Click 2 Here

code behind:

myLink.Href = Page.ResolveClientUrl("~/MyPage.aspx") + "?id=" + 
   Server.UrlEncode("put here what ever you want to url encode"); 

Or as in your question:

myLink.Href = "http://www.google.com/")+Server.UrlEncode("C#");

this 1 will put in html:

<a id="myLink" runat="server" target="_self" href="http://www.google.com/c+c%23">

More Related questions