C# 有没有办法将所有查询字符串名称/值对放入一个集合中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2375372/
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-07 01:54:01  来源:igfitidea点击:

Is there a way to get all the querystring name/value pairs into a collection?

c#asp.netcollectionsquery-string

提问by Blankman

Is there a way to get all the querystring name/value pairs into a collection?

有没有办法将所有查询字符串名称/值对放入一个集合中?

I'm looking for a built in way in .net, if not I can just split on the & and load a collection.

我正在寻找 .net 中的内置方式,如果没有,我可以在 & 上拆分并加载一个集合。

采纳答案by Andrew Hare

Yes, use the HttpRequest.QueryStringcollection:

是的,使用HttpRequest.QueryString集合:

Gets the collection of HTTP query string variables.

获取 HTTP 查询字符串变量的集合。

You can use it like this:

你可以这样使用它:

foreach (String key in Request.QueryString.AllKeys)
{
    Response.Write("Key: " + key + " Value: " + Request.QueryString[key]);
}

回答by Joel Mueller

Well, Request.QueryStringalready IS a collection. Specifically, it's a NameValueCollection. If your code is running in ASP.NET, that's all you need.

嗯,Request.QueryString已经是一个集合。具体来说,它是一个NameValueCollection. 如果您的代码在 ASP.NET 中运行,这就是您所需要的。

So to answer your question: Yes, there is.

所以回答你的问题:是的,有。

回答by Asad

QueryStringproperty in HttpRequestclass is actually NameValueCollectionclass. All you need to do is

QueryStringHttpRequest类中的属性实际上是NameValueCollection类。你需要做的就是

NameValueCollection col = Request.QueryString;

NameValueCollection col = Request.QueryString;

回答by jishi

If you have a querystring ONLY represented as a string, use HttpUtility.ParseQueryStringto parse it into a NameValueCollection.

如果您有一个仅表示为字符串的查询字符串,请使用HttpUtility.ParseQueryString将其解析为 NameValueCollection。

However, if this is part of a HttpRequest, then use the already parsed QueryString-property of your HttpRequest.

但是,如果这是 HttpRequest 的一部分,则使用已解析的 HttpRequest 的 QueryString 属性。

回答by M. Salah

You can use LINQ to create a List of anonymous objects that you can access within an array:

您可以使用 LINQ 创建一个可以在数组中访问的匿名对象列表:

var qsArray = Request.QueryString.AllKeys
    .Select(key => new { Name=key.ToString(), Value=Request.QueryString[key.ToString()]})
    .ToArray();