如何以字典的形式访问所有查询字符串参数 [英] How to access all querystring parameters as a dictionary

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

问题描述

我有一些动态查询字符串参数,我想将它们作为 IDictionary 进行交互.我该怎么做?

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)

按照建议 但对于

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

它总是给我一本包含 0 个条目的字典.

it always gives me a dictionary with 0 items.

我什至不需要 selections 前缀.我真的只需要所有查询字符串参数作为字典.我该怎么做,为什么上述方法不起作用?

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?

推荐答案

您可以使用 HttpRequestMessage 上的GetQueryNameValuePairs 扩展方法 以获取解析的查询字符串作为键值集合对.

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

您可以创建一些进一步的扩展方法,使其更易于使用,如下所述:WebAPI:获取标题、QueryString 和 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天全站免登陆