【发布时间】:2018-11-20 08:32:06
【问题描述】:
我正在编写一个 ActionFilterAttribute,我在其中检查 userId 路由/查询参数并将其与 jwt 令牌的主题进行比较。我注意到我的动作过滤器被触发了两次。在 chrome 中,我可以看到一个 OPTIONS 请求被发送到服务器,在我的调试控制台输出中,我可以看到使用正确的 http 方法的调用:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 OPTIONS http://localhost:5000/api/v1/users/33417
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:5000/api/v1/users/33417 application/json
但是当它到达我的操作过滤器时,Http 方法总是设置为 GET,所以我不能让我的过滤器在 OPTIONS 调用时返回。
这是一个基本的 OnActionExecutionAsync 覆盖方法:
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
Debug.WriteLine("URL CALL: " + context.HttpContext.Request.GetDisplayUrl());
Debug.WriteLine("HTTP METHOD: " + context.HttpContext.Request.Method);
if (HttpMethods.IsOptions(context.HttpContext.Request.Method))
{
Debug.WriteLine("HTTP METHOD: OPTIONS");
return base.OnActionExecutionAsync(context, next);
}
// Other Code ....
}
调试日志:
URL CALL: http://localhost:5000/api/v1/users/33417
HTTP METHOD: GET
URL CALL: http://localhost:5000/api/v1/users/33417
HTTP METHOD: GET
另一个有趣的点是,如果我从 Postman 工具请求 OPTIONS,我的 API 会返回以下错误消息:
{
"error": {
"code": "UnsupportedApiVersion",
"message": "The HTTP resource that matches the request URI 'http://localhost:5000/api/v1/users/33417' with API version '1' does not support HTTP method 'OPTIONS'.",
"innerError": null
}
}
这是我在启动时的 Cors 配置:
services.AddCors(options => options.AddPolicy(_constants.CorsPolicy,
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build()));
有什么方法可以在我的操作过滤器中捕获 OPTIONS http 方法?
【问题讨论】:
-
项目是否配置了CORS?
-
是的,配置为
AllowAnyMethod() -
那就是答案,CORS 中间件正在处理 OPTIONS 请求,而您的过滤器看到的是 OPTIONS 请求之后的 GET 请求。
标签: c# asp.net-web-api asp.net-core .net-core actionfilterattribute