简体   繁体   中英

Dangerous Request.Cookies value was detected from the client

I am in quite the situation here at work as I´m all of a sudden starts getting this error:

An exception of type 'System.Web.HttpRequestValidationException' occurred in System.Web.dll but was not handled in user code

Additional information: A potentially dangerous Request.Cookies value was detected from the client (CustomerRegionName="&#214").

I know that there are several threads about this issue already, and I´ve tried all of the answers I have seen, the most common being the following:

Use httpRuntime requestValidationMode="2.0"
in your web.config (keeping any attributes you already have on that element, if it's already there). ASP.NET4.0 ignores ValidateRequest otherwise. Taken from: Here

I am building a website where most input is in Swedish, so to prevent browserproblems I encode all cookie values with the help of HttpUtility class.

That means that A value like "Örebro" will be encoded to something like this: %c3%96rebro.

And for some reason .net framework thinks that this is some kind of dangerous value.

I have absolutely no idea what to do here... Any help would be greatly appreciated.

To avoid this error, convert your string into a hexadecimal representation of the string. This can be done with code like this:

string ConvertedString = BitConverter.ToString(Encoding.Default.GetBytes(YourString));

Note that this string will have the hex separated into pairs with "-" (ie, 4f-cc-12-ab).

When you read it back, restore it to the original string with code like this, assuming your read the encoded string back into string zBackInHex:

string zHex = (zBackInHex.Replace("-", "");
byte[] ba = new byte[zHex.Length / 2];  //One byte for each two chars in zHex
for(int ZZ = 0; ZZ < ba.Length; ZZ++){
   ba[ZZ] = Convert.ToByte(zHex.Substring(ZZ * 2, 2), 16);
}
string zBackIn = Encoding.ASCII.GetString(ba);  //The original string

I got the idea for this method from another post. I'd give credit, but I don't remember where I originally saw it.

Why don't you try to replace strings with IDs, that will remove all the hassle with encoding. Create lookup table with region ID, RegionName. Pass ID to your cookie, and there will be no problem with dangerous requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM