How to access all querystring parameters as a dictionary

后端 未结 2 713
北恋
北恋 2020-12-08 02:30

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

I tried

2条回答
  •  轮回少年
    2020-12-08 02:52

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

    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

    /// 
    /// Extends the HttpRequestMessage collection
    /// 
    public static class HttpRequestMessageExtensions
    {
        /// 
        /// 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.
        /// 
        /// 
        /// 
        public static Dictionary GetQueryStrings(
            this HttpRequestMessage request)
        {
             return request.GetQueryNameValuePairs()
                           .ToDictionary(kv => kv.Key, kv=> kv.Value, 
                                StringComparer.OrdinalIgnoreCase);
        }
    }
    

提交回复
热议问题