Code Project

Link Unit

Tuesday, December 18, 2007

Using HttpUtility.UrlEncode

Perhaps the most popular way to pass data between web-pages is by using querystring. This is used to both pass data to a new pop-up window, as well as to navigate between pages.
Querystring passes data in name value pair , where names are separated by &. So querystring would be something similar to
name1=value1&name2=value2 etc . Now if the value itself contains & ,then wrong values would be extracted
Go through this link to know why we need urlencoding.
This method is good for passing simple alpha-numeric data, but it can be a problem to pass special characters in the URL, especially in different browsers.
· An ampersand would split the name-value pairs. (If you want to pass the value "Johnson&Johnson baby", but the & indicates a new name-value pair, then the value will be truncated to just " Johnson ". For example, in "id= Johnson&Johnson baby ", getting the querystring "id" will return just " Johnson ", and "Johnson baby" will be interpreted as its own key.
· Apostrophes, greater than or less than signs may be interpreted as a cross-site scripting attack by some security plug-ins. As a result, these plug-ins may block the entire page.
· Other special characters (like slash or space) may be lost or distorted when sending them into a url.
Fortunately there is a solution to handling special characters. .Net provides us the ability to Encode and Decode the URL using System.Web.HttpUtility.UrlEncode and HttpUtility.UrlDecode
(note that HtmlEncode, which encodes html, and won't affect the &.). This replaces problematic characters with URL-friendly equivalents.

Post a Comment