Best way to convert query string to dictionary in C#

Viewed 59789

I'm looking for the simplest way of converting a query string from an HTTP GET request into a Dictionary, and back again.

I figure it's easier to carry out various manipulations on the query once it is in dictionary form, but I seem to have a lot of code just to do the conversion. Any recommended ways?

14 Answers

HttpUtility.ParseQueryString() parses query string into a NameValueCollection object, converting the latter to an IDictionary<string, string> is a matter of a simple foreach. This, however, might be unnecessary since NameValueCollection has an indexer, so it behaves pretty much like a dictionary.

In ASP.NET Core, use ParseQuery.

var query = HttpContext.Request.QueryString.Value;
var queryDictionary = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(query);

Instead of converting HttpContext.Request.QueryString to Dictionary<>, try using

HttpContext.Request.Query

which already is a Dictionary<string, StringValues>

I stumbled across this post whilst looking for the same solution for an Azure WebJob, hopefully this helps others doing the same.

If you are coding an Azure WebJob you use the GetQueryParameterDictionary() extension method.

var queryParameterDictionary = request.GetQueryParameterDictionary();

where request is of type HttpRequest and queryParameterDictionary is now of type IDictionary<string, string>

You can just get it by decorating the parameter with the FromQueryAttribute

public void Action([FromQuery] Dictionary<string, string> queries)
{
    ...
}

P.S. If you want to get multiple values for each key you can change the Dictionary to Dictionary<string, List<string>>

AspNet Core now automatically includes HttpRequest.Query which can be used similar to a dictionary with key accessors.

However if you needed to cast it for logging or other purposes, you can pull out that logic into an extension method like this:

public static class HttpRequestExtensions
{
  public static Dictionary<string, string> ToDictionary(this IQueryCollection query)
  {
    return query.Keys.ToDictionary(k => k, v => (string)query[v]);
  }
}

Then, you can consume it on your httpRequest like this:

var params = httpRequest.Query.ToDictionary()

Further Reading

Related