46

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

I tried

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

as suggested but for a query of

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

it always gives me a dictionary with 0 items.

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?

George Mauer
  • 117,483
  • 131
  • 382
  • 612

3 Answers3

69

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

/// <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);
    }
}
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • 1
    There's an interesting comment on that web page post though which is that "This will throw an exception for duplicate key, if a query parameter is repeated". Note that repeated querystring keys is perfectly valid URL syntax. – Carlos P Jul 20 '15 at 17:17
  • If the querystring contains an encoded & (ampersand), like this: `?key=value1%26value2%26value3` then the keys get "split" at the & character (you end up with 3 dictionary entries instead of 1). What's the reason for this? – Andrew Gee Oct 02 '15 at 15:10
2

In addition to what nemesv mentioned, you can also create a custom parameter binding for IDictionary<string,string> similar to the approach I show here:

How would I create a model binder to bind an int array?

Community
  • 1
  • 1
Kiran
  • 56,921
  • 15
  • 176
  • 161
1

We can use HttpUtility.ParseQueryString(<string>) method from System.Web namespace. This method will parse the query string given as input and return it as an NameValueCollection.

sprash95
  • 137
  • 9