在 C# 中将查询字符串转换为字典的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/776107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:41:47  来源:igfitidea点击:

Best way to convert query string to dictionary in C#

c#

提问by

I'm looking for the simplest way of converting a query string from an HTTP GET request into a Dictionary, and back again.

我正在寻找将查询字符串从 HTTP GET 请求转换为字典,然后再返回的最简单方法。

I figure it's easier to carry out various manipulations on the query once it is in dictionary form, but I seem to have a lot of code just to do the conversion. Any recommended ways?

我认为一旦查询以字典形式对查询进行各种操作会更容易,但我似乎有很多代码只是为了进行转换。有什么推荐的方法吗?

回答by Marc Gravell

How about HttpUtility.ParseQueryString?

怎么样HttpUtility.ParseQueryString

Just add a reference to System.Web.dll

只需添加对 System.Web.dll 的引用

回答by Anton Gogolev

HttpUtility.ParseQueryString()parses query string into a NameValueCollectionobject, converting the latter to an IDictionary<string, string>is a matter of a simple foreach. This, however, might be unnecessary since NameValueCollectionhas an indexer, so it behaves pretty much like a dictionary.

HttpUtility.ParseQueryString()将查询字符串解析为一个NameValueCollection对象,将后者转换为 anIDictionary<string, string>是一个简单的foreach. 然而,这可能是不必要的,因为它NameValueCollection有一个索引器,所以它的行为非常像一个字典。

回答by Jon Canning

Just had to do this for a mono compatible solution

只需为单声道兼容解决方案执行此操作

Regex.Matches(queryString, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[3].Value)

回答by nemesisfixx

I like the brevity of Jon Canning's answer, but in the interest of variety, here is another alternative to his answer, that would also work for restricted environments like Windows Phone 8, that lack the HttpUtility.ParseQueryString()utility:

我喜欢Jon Canning 回答的简洁性,但出于多样性的考虑,这是他回答的另一种替代方法,它也适用于 Windows Phone 8 等缺乏HttpUtility.ParseQueryString()实用程序的受限环境:

    public static Dictionary<string, string> ParseQueryString(String query)
    {
        Dictionary<String, String> queryDict = new Dictionary<string, string>();
        foreach (String token in query.TrimStart(new char[] { '?' }).Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
        {
            string[] parts = token.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 2)
                queryDict[parts[0].Trim()] = HttpUtility.UrlDecode(parts[1]).Trim();
            else
                queryDict[parts[0].Trim()] = "";
        }
        return queryDict;
    }

Actually, a useful improvement to Canning's answer that take care of decoding url-encoded values (like in the above solution) is:

实际上,对 Canning's answer 的一个有用的改进是:

    public static Dictionary<string, string> ParseQueryString2(String query)
    {
       return Regex.Matches(query, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => HttpUtility.UrlDecode( x.Groups[3].Value ));
    }

回答by H7O

Here is how I usually do it

这是我通常的做法

Dictionary<string, string> parameters = HttpContext.Current.Request.QueryString.Keys.Cast<string>()
    .ToDictionary(k => k, v => HttpContext.Current.Request.QueryString[v]);

回答by vicentedealencar

One liner without HttpUtility

一个没有 HttpUtility 的班轮

var dictionary = query.Replace("?", "").Split('&').ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1]);

回答by Sean Colombo

Yet another way to do it:

另一种方法来做到这一点:

NameValueCollection nvcData = HttpUtility.ParseQueryString(queryString);
Dictionary<string, string> dictData = new Dictionary<string, string>(nvcData.Count);
foreach (string key in nvcData.AllKeys)
{
    dictData.Add(key, nvcData.Get(key));
}

回答by ThisGuy

Same as Sean, but with Linq (and a function you can copy and paste):

与 Sean 相同,但使用 Linq(以及您可以复制和粘贴的功能):

public static Dictionary<string, string> ParseQueryString(string queryString)
{
   var nvc = HttpUtility.ParseQueryString(queryString);
   return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);
}

Also, the question asked how to get it back into a query string:

此外,该问题询问如何将其恢复为查询字符串:

public static string CreateQueryString(Dictionary<string, string> parameters)
{
   return string.Join("&", parameters.Select(kvp => 
      string.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))));
}

回答by Bruno Leit?o

Most simple:

最简单:

Dictionary<string, string> parameters = new Dictionary<string, string>();

for (int i = 0; i < context.Request.QueryString.Count; i++)
{
    parameters.Add(context.Request.QueryString.GetKey(i), context.Request.QueryString[i]);
}

回答by James Lawruk

In ASP.NET Core, use ParseQuery.

在 ASP.NET Core 中,使用ParseQuery

var query = HttpContext.Request.QueryString.Value;
var queryDictionary = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(query);