简体   繁体   English

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

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

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 中的内置方式,如果没有,我可以在 & 上拆分并加载一个集合。

Yes, use the HttpRequest.QueryString collection: 是的,使用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]);
}

Well, Request.QueryString already IS a collection. 好吧, Request.QueryString已经是一个集合。 Specifically, it's a NameValueCollection . 具体来说,它是一个NameValueCollection If your code is running in ASP.NET, that's all you need. 如果您的代码在ASP.NET中运行,那就是您所需要的。

So to answer your question: Yes, there is. 所以回答你的问题:是的,有。

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();

If you have a querystring ONLY represented as a string, use HttpUtility.ParseQueryString to 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属性。

QueryString property in HttpRequest class is actually NameValueCollection class. HttpRequest类中的QueryString属性实际上是NameValueCollection类。 All you need to do is 你需要做的就是

NameValueCollection col = Request.QueryString; NameValueCollection col = Request.QueryString;

Create dictionary of parameters创建参数字典

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM