Server.UrlEncode in ASP and ASP.NET

by Peter Ravnholt 21. November 2007 13:33

In our process of migrating parts of a large site from traditional ASP to ASP.NET, we encountered a problem with Server.UrlEncode and special characters:

If the ASP page does something like:

[code:c#]

param = "These characters are special: Æ Ø Å"
param = Server.URLEncode(param)
Response.Redirect("MyAspNetPage.aspx?p=" & param)

[/code]

And the recieving ASP.NET page does a

[code:c#]

string param = Request.QueryString["p"];

[/code]

The result is not the original encoded text, but some garbage characters. The problem is that the default encoding is different between the two platforms.

We need to do two workarounds:

First, double-encode on the ASP page:

[code:c#]

param = "These characters are special: Æ Ø Å"
param = Server.URLEncode(Server.URLEncode(param))
Response.Redirect("MyAspNetPage.aspx?p=" & param)

[/code]

On the ASP.NET side the Request.QueryString implicitly url decodes using the default encoding, which is not what we want. By double-encoding on the ASP page, we get a chance to tell the framework to use a specific encoding when url decoding the second level. The trick is not to use the Server object, but the HttpUtility class instead.:

[code:c#]

string param = HttpUtility.UrlDecode(Request.QueryString["p"], System.Text.Encoding.GetEncoding("ISO-8859-1"));

[/code]

The ISO-8859-1 is the default encoding for traditional ASP in our case. Now the recieved and parsed querystring is the same as the original intended.

Please note that the UrlDecode method of the HttpUtility class is different than the one exposed by the Server object (which actually maps to the HttpServerUtility class). I would recommend using the HttpUtility methods as these provide more functionality - like specifying the encoding.

Going from ASP.NET to ASP is easier - just use the HttpUtility.UrlEncode on the ASP.NET page to encode a query string for an ASP page.

Tags: , ,

.NET development

Comments

10/22/2011 5:48:39 PM #

Monalisa Smith

Nice information.....thanks

Monalisa Smith United States

4/26/2012 8:42:17 PM #

Rental Car Dubai

Thanks for the kind words poo, this is incidentaly my fav post also. keep on chekng, more stuff coming.

Rental Car Dubai Afghanistan

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.1.0

About the author

Peter Ravnholt

My Delicious bookmarks

Email

Peter Ravnholt is working as a .NET software architect and lead developer.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

 


© Copyright 2009, Peter Ravnholt


Creative Commons License

Peter's .NET Ramblings
is licensed under a Creative Commons Navngivelse 3.0 Unported License.
Permissions beyond the scope of this license may be available at the contact page.