VKamakodu

UrlEncoding querystring value

Discussion created by VKamakodu on Nov 19, 2008
Latest reply on Dec 25, 2008 by cescamilla

Passing query string values between pages is one of the common tasks in web programming. You would do something like this: Response.Redirect ("Mypage.aspx?ID=200") and MyPage.aspx will show some details based on value 200.

 

I came across a problem yesterday where the page didn't show any details based on the querystring value that was passed. After some debugging, found out that the value I passed from the first page and the value that was recieved on the second page were not the same. My querystring value is a string. It looks something like this: MyPage.apsx?ID=abc+45:90.... As you can see, there is a + sign. On the second page, "+" was stripped off, so obviously the values are diffrent. I don't have any control over the format of the ID because it is generated automatically.

 

Why did my value change? The reason this happens is because there are certain special characters ("#" "/", "<" etc) that are not allowed in the querystring as they carry special meaning or not valid characters for url. But if you do want to pass those, then you would need to encode them. Then the browser would encode "+" with "%2b" and lets the value passthrough.

 

In .net you can use HttpUtility.UrlEncode method to pass value safely. Now this is nothing new, something every developer has used before. Usually this is not a problem if you have static or hardcoded or numeric values. But if you have string values and you don't know what they look like, it's best practice to always use UrlEncode.

 

Anyways, now my code line looks like this and works.

 

Response.Redirect("MyPage.apsx?ID=" + HttpUtility.UrlEncode(abc+45:90....));

 

Moral of the story? Remember your basics!

Outcomes