Friday 2 March 2012

Query string encoding in asp.net

The .NET Framework provides the HttpServerUtility.UrlEncode class to encode the URL.
The following code shows how name and id is passed to abc.aspx page as encoded.
  string id = "11";
  string name = "abc";
  string url = string.Format("abc.aspx?{0}&{11}", Server.UrlEncode(id), 
  Server.UrlEncode(name));
  Response.Redirect(url);

  // decoding can be done using it's counter part HttpServerUtility.UrlDecode()

  string id = Server.UrlDecode(Request.QueryString["id"]);
  string name = Server.UrlDecode(Request.QueryString["name"]);
 

Note: HttpServerUtility is available to your code in all webforms through the Page.Server property. Also you only need to encode those values which have non-ASCII characters, not all the values.

No comments:

Post a Comment