November 21, 2007

Server.UrlEncode in ASP and ASP.NET

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:

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

And the recieving ASP.NET page does a

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

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:

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

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.:

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

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.

No comments:

Post a Comment