Is really QueryString case insensitive?

懵懂的女人 提交于 2019-12-05 09:42:19

Unfortunately, the API doesn't provide a way to make the Request.QueryString collection case sensitive (or the Request.Headers or Request.Form collections, for that matter).

However, with a bit of reverse engineering via reflection, it is not that difficult to do.

public class CaseSensitiveQueryStringCollection : System.Collections.Specialized.NameValueCollection
{
    public CaseSensitiveQueryStringCollection(string queryString, bool urlencoded, System.Text.Encoding encoding)
        // This makes it case sensitive, the default is StringComparer.OrdinalIgnoreCase
        : base(StringComparer.Ordinal)
    {
        if (queryString.StartsWith("?"))
        {
            queryString = queryString.Substring(1);
        }

        this.FillFromString(queryString, urlencoded, encoding);
    }

    internal void FillFromString(string s, bool urlencoded, System.Text.Encoding encoding)
    {
        int num = (s != null) ? s.Length : 0;
        for (int i = 0; i < num; i++)
        {
            int startIndex = i;
            int num4 = -1;
            while (i < num)
            {
                char ch = s[i];
                if (ch == '=')
                {
                    if (num4 < 0)
                    {
                        num4 = i;
                    }
                }
                else if (ch == '&')
                {
                    break;
                }
                i++;
            }
            string str = null;
            string str2 = null;
            if (num4 >= 0)
            {
                str = s.Substring(startIndex, num4 - startIndex);
                str2 = s.Substring(num4 + 1, (i - num4) - 1);
            }
            else
            {
                str2 = s.Substring(startIndex, i - startIndex);
            }
            if (urlencoded)
            {
                base.Add(HttpUtility.UrlDecode(str, encoding), HttpUtility.UrlDecode(str2, encoding));
            }
            else
            {
                base.Add(str, str2);
            }
            if ((i == (num - 1)) && (s[i] == '&'))
            {
                base.Add(null, string.Empty);
            }
        }
    }
}

Usage

var query = new CaseSensitiveQueryStringCollection(
    HttpContext.Current.Request.Url.Query, 
    true, 
    System.Text.Encoding.UTF8);

When you use a querystring like ?MAC=123&mac=456, you can see they are kept separate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!