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
Most simple:
Dictionary<string, string> parameters = new Dictionary<string, string>();
for (int i = 0; i < context.Request.QueryString.Count; i++)
{
parameters.Add(context.Request.QueryString.GetKey(i), context.Request.QueryString[i]);
}
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>>
Here is how I usually do it
Dictionary<string, string> parameters = HttpContext.Current.Request.QueryString.Keys.Cast<string>()
.ToDictionary(k => k, v => HttpContext.Current.Request.QueryString[v]);
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>
Instead of converting HttpContext.Request.QueryString to a Dictionary<>, try using
HttpContext.Request.Query which already is a Dictionary<string, StringValues>
One liner without HttpUtility
var dictionary = query.Replace("?", "").Split('&').ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1]);