How to get a querystring when it is URLEncoded or has percent characters in ASP.NET

霸气de小男生 提交于 2019-12-19 10:32:26

问题


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?


回答1:


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!




回答2:


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"])



回答3:


HttpContext.Current.Request.ServerVariables["QUERY_STRING"]

will return the RAW Query String




回答4:


I had the same problem. I solved it just by adding in javascript "escape('text % text')" while contructing the querystring!



来源:https://stackoverflow.com/questions/1638499/how-to-get-a-querystring-when-it-is-urlencoded-or-has-percent-characters-in-asp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!