Best way to convert query string to dictionary in C#

前端 未结 13 876
温柔的废话
温柔的废话 2020-12-24 04:28

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

相关标签:
13条回答
  • 2020-12-24 05:03

    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]);
    }
    
    0 讨论(0)
  • 2020-12-24 05:07

    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>>

    0 讨论(0)
  • 2020-12-24 05:13

    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]);
    
    0 讨论(0)
  • 2020-12-24 05:14

    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>

    0 讨论(0)
  • 2020-12-24 05:20

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

    HttpContext.Request.Query which already is a Dictionary<string, StringValues>
    
    0 讨论(0)
  • 2020-12-24 05:21

    One liner without HttpUtility

    var dictionary = query.Replace("?", "").Split('&').ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1]);
    
    0 讨论(0)
提交回复
热议问题