Description
The HttpUtility.ParseQueryString() method returns a NameValueCollection
that can be modified and then converted back to a string to produce a new query string.
However, the behavior of the .ToString()
method that produces that string varies based on app settings and execution environment:
- Under some circumstances, keys and values are escaped using
HttpUtility.UrlEncodeUnicode()
, which encodes®
as%u00ae
(unicode encoding) - Under other circumstances, keys and values are escaped using
HttpUtility.UrlEncode()
, which encodes®
as%c2%ae
(UTF8 encoding)
// q is either "a=%c2%a9&b=%c2%ae" or "a=%u00a9&b=%u00ae"
var q = HttpUtility.ParseQueryString("a=%c2%a9&b=%c2%ae").ToString();
To the best of my understanding, this behavior is determined as follows:
- If the app has an appSetting with key
aspnet:DontUsePercentUUrlEncoding
and valuetrue
orfalse
, then it will use UTF8 encoding fortrue
and unicode encoding forfalse
- Otherwise, if it is an ASP.NET app with a
targetFramework
of 4.5.2+ in its web.config, it will use UTF8 encoding- I'm not sure in what way this applies to ASP.NET Core apps, or if other factors are taken into account in determining the target framework
- Otherwise, it will use unicode encoding
Clearly this behavior is quite confusing, and as far as I can tell, there is no documentation on it. I think it would be ideal if this were documented.
I would be happy to submit a pull request for the HttpUtility.ParseQueryString documentation, but I am not clear on the full nuances of this behavior, and am not sure what would be the best way to describe it in the documentation. I would be grateful if someone could give me a push in the right direction.