How to get a querystring when it is URLEncoded or

2020-03-28 03:29发布

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?

4条回答
我想做一个坏孩纸
2楼-- · 2020-03-28 04:10

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!

查看更多
该账号已被封号
3楼-- · 2020-03-28 04:17

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

查看更多
▲ chillily
4楼-- · 2020-03-28 04:27
HttpContext.Current.Request.ServerVariables["QUERY_STRING"]

will return the RAW Query String

查看更多
戒情不戒烟
5楼-- · 2020-03-28 04:29

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"])
查看更多
登录 后发表回答