Monday, 3 May 2010

Query String Encoding Hassles with & in ASP.Net

Today I encountered an odd problem which I remember having years ago but had no memory of how to solve it....

So I'm creating a URL with a query string which will appear in a web page:
thumbnailImage.ImageUrl =  "~/UserControls/ImageHandler.ashx?" + "id=" + productImages[0].UId + "&thumb=true&size=100"
Now when this appears in the web page, it seems that all of the "&" symbols, which represent the delimiter between parameters, get changed to "&"

The problem with this is that when the page that is linked to resolves the query parameters I get:


The first thing I tried was to use Server.URLEncode. This changes the "&" symbols to "%26". This in itself is no use, but when used with Server.URLDecode means we end up with the correct query string. It still gives us a problem however because we can no longer use the string index for context.Request.Params. We'd have to manually parse the string output of URLDecode to find the required parameter. Not difficult I know, but a little untidy.

The solution I eventually found was to use:
thumbnailImage.ImageUrl = String.Format("~/UserControls/ImageHandler.ashx?" + "id=" + productImages[0].UId + "&thumb=true&size=100");
It appears that the String.Format causes the "&" symbols not to be changed to "&"

Exactly why that happens I do not know, it seems that the output of String.Format is the same as the original string:

String.Format("~/UserControls/ImageHandler.ashx?" + "id=" + productImages[0].UId + "&thumb=true&size=100").Equals("~/UserControls/ImageHandler.ashx?" + "id=" + productImages[0].UId + "&thumb=true&size=100")
Strange... but it seems to work.

No comments:

Post a Comment