dotnet / dotnet/dotnet-api-docs

Re-serializing query parsed with HttpUtility.ParseQueryString() has confusing, undocumented behavior

Open
#5,119 1 comment 0 reactions 0 assignees View on GitHub
area-System.Net.Http Pri3 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

The [HttpUtility.ParseQueryString()](https://docs.microsoft.com/en-us/dotnet/api/system.web.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)

```c#
// 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 value `true` or `false`, then it will use UTF8 encoding for `true` and unicode encoding for `false`
- 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](https://docs.microsoft.com/en-us/dotnet/api/system.web.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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.