我在几行将值从查询字符串中拉出的代码中观察到一些奇怪/无法预期的行为。

函数调用

ValidateRequestNameValueCollection(HttpContext.Current.Request.Headers // other params omitted


功能定义

 private void ValidateRequestNameValueCollection(NameValueCollection nvc, // other params omitted
        {
            int count = nvc.Count;

            validationFailureIndex = 0;

            for (int index = 0; index < count; ++index)
            {
                string key = nvc.GetKey(index);

                if (null != key && key.StartsWith(DoubleUnderline, StringComparison.Ordinal))
                    continue;

                string str = nvc.Get(index); // this is returning a decoded string


在Visual Studio调试器中,如果将鼠标悬停在NameValueCollection参数上,则会看到类似以下内容:

{param = omitted3GCDqHrqg5w%2b6NJfc%3d}

可以清楚地进行编码,但是当调用.get时,返回的字符串将被解码。基于此处的答案:HttpValueCollection and NameValueCollection我认为NameValueCollection参数是无提示转换为HttpValueCollection的,并且HttpValueCollection在获取时自动调用UrlDecode。我找不到任何明确说明这一点的文档。有人知道吗?

最佳答案

请参见https://referencesource.microsoft.com/#System.Web/HttpValueCollection.cshttps://github.com/Microsoft/referencesource/blob/master/System.Web/HttpValueCollection.cs

internal void FillFromString(String s, bool urlencoded, Encoding encoding) {
    ...
    if (urlencoded)
        base.Add(
            HttpUtility.UrlDecode(name, encoding),
            HttpUtility.UrlDecode(value, encoding));
    else
        ...

关于c# - 为什么Request.QueryString.Get()和NameValueCollection.Get()返回解码后的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48670131/

10-09 17:46