如何访问所有查询字符串参数作为一个字典 [英] How to access all querystring parameters as a dictionary

查看:324
本文介绍了如何访问所有查询字符串参数作为一个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些动态的查询字符串参数,我想与为的IDictionary&LT交互;字符串,字符串> 。我该怎么做呢?

I have some dynamic querystring parameters that I would like to interact with as an IDictionary<string,string>. How do I do this?

我试过

public IHttpActionResult Get(FromUri]IDictionary<string, string> selections)

<一个href=\"http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx\">as建议但对于查询

/api/MyController?selections%5Bsub-category%5D=kellogs

它总是给我0项的字典。

it always gives me a dictionary with 0 items.

我甚至都不需要 preFIX。我真的只是需要的所有查询字符串参数作为一个字典。我如何做到这一点,为什么不将上述工作?

I don't even need the selections prefix. I literally just need all querystring parameters as a dictionary. How do I do this and why won't the above work?

推荐答案

您可以使用<$c$c>GetQueryNameValuePairs在扩展方法中的的Htt prequestMessage 来得到解析的查询字符串键值对的集合。

You can use the GetQueryNameValuePairs extension method on the HttpRequestMessage to get the parsed query string as a collection of key-value pairs.

public IHttpActionResult Get()
{
    var queryString = this.Request.GetQueryNameValuePairs();
}

和您可以创建一些进一步的扩展方法,使其eaiser与此处描述的工作:<一href=\"http://weblog.west-wind.com/posts/2013/Apr/15/WebAPI-Getting-Headers-QueryString-and-Cookie-Values\">WebAPI:获得接头,查询字符串和cookie值

And you can create some further extension methods to make it eaiser to work with as described here: WebAPI: Getting Headers, QueryString and Cookie Values

/// <summary>
/// Extends the HttpRequestMessage collection
/// </summary>
public static class HttpRequestMessageExtensions
{
    /// <summary>
    /// Returns a dictionary of QueryStrings that's easier to work with 
    /// than GetQueryNameValuePairs KevValuePairs collection.
    /// 
    /// If you need to pull a few single values use GetQueryString instead.
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static Dictionary<string, string> GetQueryStrings(
        this HttpRequestMessage request)
    {
         return request.GetQueryNameValuePairs()
                       .ToDictionary(kv => kv.Key, kv=> kv.Value, 
                            StringComparer.OrdinalIgnoreCase);
    }
}

这篇关于如何访问所有查询字符串参数作为一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆