如何获取Request Querystring值?

loy*_*low 11 c# asp.net-mvc asp.net-web-api

我的api客户端代码在查询字符串中发送身份验证令牌,如:

www.example.com/api/user/get/123?auth_token=ABC123
Run Code Online (Sandbox Code Playgroud)

我正在使用Mvc Web api控制器,我有一个过滤器来检查auth_token是否有效,但我不知道如何访问请求查询字符串值.

这就是我现在正在做的事情,但显然是错误的:

以下代码段位于我的过滤器内部,该过滤器继承自:

ActionFilterAttribute

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
       base.OnActionExecuting(actionContext);

       if (actionContext.Request.Properties.ContainsKey("auth_token") &&
          actionContext.Request.Properties["auth_token"].ToString() == "ABC123")
       {
         ...
       }
}
Run Code Online (Sandbox Code Playgroud)

Sip*_*tra 27

使用GetQueryNameValuePairs扩展方法,如下所示:

var queryString = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)

编辑 为避免重复键,请考虑执行以下操作ToLookup:

var queryString = actionContext.Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)

这是一篇关于Lookups的博客文章:https://www.c-sharpcorner.com/UploadFile/vendettamit/using-lookup-for-duplicate-key-value-pairs-dictionary/

  • 请注意:`ToDictionary`会在传递两个具有相同键的参数时抛出异常 - 例如 - [定义一个数组](/sf/ask/698693131/ -to-ASP净网页API). (5认同)
  • 你说得对。更好的方法是使用“ToLookup”来投影名称/值对。 (2认同)

Bad*_*dri 7

OnActionExecuting过滤器的方法中,您可以访问查询字符串并像这样解析它以获取令牌.

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

但是,在查询字符串中传递令牌是一种好习惯吗?可能不是,但这取决于你.HTTP标头可能是更好的选择,因为查询字符串可以被记录和缓存.