How to get Request Querystring values?

后端 未结 3 566
鱼传尺愫
鱼传尺愫 2020-12-31 09:30

My api client code sends an authentication token in the querystring like:

www.example.com/api/user/get/123?auth_token=ABC123

I\'m using Mvc

相关标签:
3条回答
  • 2020-12-31 09:53

    Use the GetQueryNameValuePairs extension method, like so:

    var queryString = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
    

    EDIT To avoid duplicate keys, consider doing a ToLookup:

    var queryString = actionContext.Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);
    

    Here's a blog post on Lookups: https://www.c-sharpcorner.com/UploadFile/vendettamit/using-lookup-for-duplicate-key-value-pairs-dictionary/

    0 讨论(0)
  • 2020-12-31 10:04

    In the OnActionExecuting method of a filter, you can access the query string and parse it like this to get the token.

    var queryString = actionContext.Request.RequestUri.Query;
    if(!String.IsNullOrWhiteSpace(queryString))
    {
        string token = HttpUtility.ParseQueryString(
                             queryString.Substring(1))["auth_token"];
    }
    

    But then, is passing a token in query string a good practice? Probably not, but it is up to you. HTTP header could be a better option since query string can get logged and cached.

    0 讨论(0)
  • 2020-12-31 10:16

    Another way to do it, similar to Badri's:

    string qsValue = string.Empty;
    if (Request.QueryString.HasValue)
    {
       NameValueCollection queryStringNameValues = HttpUtility.ParseQueryString(Request.QueryString.Value);
       qsValue = queryStringNameValues.Get("auth_token");
    }
    
    0 讨论(0)
提交回复
热议问题