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/
在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标头可能是更好的选择,因为查询字符串可以被记录和缓存.
| 归档时间: |
|
| 查看次数: |
26843 次 |
| 最近记录: |