views:

925

answers:

3

How to get the actual querystring from the Request object when the querystring is UrlEncoded or has percent characters in ASP.NET?

Basicly, if I have a Url like this: Default.aspx?p=%b4, how do I get a string populated with "%b4"?

Request.QueryString["p"] returns a non printable character.

Request.RawUrl returns Default.aspx?p=%ufffd"

Request.Url.AbsoluteUri returns Default.aspx?p=%EF%BF%BD

How can I get "%b4" back?

Thanks for your help.

+2  A: 

I dug into this further, and believe I know what's causing this: an HTTP client is submitting a URL to the server which is not properly URL-encoded. Specifically, there is an invalid character in the URL.

To repro, paste the following at the end of your URL into IE8: default.aspx?p=´

If you examine the bytes going over the wire (e.g. using Fiddler), you'll see an actual Hex B4 character is being sent from client to server in the URL. This is an illegal character in a URL, since URLs are limited to char codes under 0x80 (any larger-than-0x80 char codes must be percent-escaped).

So your client is passing in an invalid character, and your server is (correctly) replacing the bogus character with %EF%BF%BD which is the UTF-8 encoding for the Unicode Replacement Character (U+0FFD), which is what happens when a character is encountered which has no equivalent in the local encoding.

AFAIK, this is a bug in IE. If you type the same URL into Firefox, Firefox will encode the URL properly (as %b4 instead of ´). Note that, also AFAIK, the problem only happens when manually pasting invalid characters into IE's address bar-- if the same character is present in a link, IE seems to encode the URL properly (at least in the cases I tested).

So you should figure out who is sending this bogus URL to you, and tell them to start encoding their URLs properly!

Justin Grant
Hmm. I tested the code above on IE8 and asp.net 3.5. I wonder if this is a browser-specific thing where the browser is doing the encoding before your code gets ahold of it? Or perhaps a .net version's behavior difference? What browser and .net version are you using? Also, what is the Request Encoding of your page? See http://msdn.microsoft.com/en-us/library/39d1w2xf.aspx for more info about encoding.
Justin Grant
Hi Justin, Thanks, I will research further.
James Lawruk
BTW, I dug into this a little more and came up with what I think is the cause of the problem you're seeing. take a look at my revised answer above.
Justin Grant
A: 
HttpContext.Current.Request.ServerVariables["QUERY_STRING"]

will return the RAW Query String

Aaron
No, this returns an unprintable character.
James Lawruk
tryHttpContext.Current.Request.ServerVariables["QUERY_STRING"]
Aaron
+1  A: 

Asp.net will automatically URL Decode stuff when you do Request.Querystring["key"]. You just need to encode it again.

HttpUtility.UrlEncode(Request.QueryString["p"])
Matthew