C# 无法捕获http请求上的HttpMethod:选项
我正在编写一个ActionFilterAttribute,其中我检查用户ID路由/查询参数,并将其与jwt令牌的主题进行比较。我注意到我的动作过滤器被触发了两次。在chrome中,我可以看到选项请求被发送到服务器,在调试控制台输出中,我可以看到使用正确http方法的调用:C# 无法捕获http请求上的HttpMethod:选项,c#,asp.net-web-api,asp.net-core,.net-core,actionfilterattribute,C#,Asp.net Web Api,Asp.net Core,.net Core,Actionfilterattribute,我正在编写一个ActionFilterAttribute,其中我检查用户ID路由/查询参数,并将其与jwt令牌的主题进行比较。我注意到我的动作过滤器被触发了两次。在chrome中,我可以看到选项请求被发送到服务器,在调试控制台输出中,我可以看到使用正确http方法的调用: Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 OPTIONS http://localhost:500
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,所以我不能让过滤器在选项调用时返回
下面是一个基本的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工具请求选项,我的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()));
有什么方法可以在我的操作筛选器中捕获选项http方法吗?因为你在应用程序上设置了CORS, 它在MVC之前响应选项飞行前请求。 该请求永远不会到达MVC,因此您的过滤器无法看到它。 过滤器看到的是选项请求之后的GET请求
app.UseCors(); //Sees OPTIONS request, sets response and returns
app.UseMvc();
您是否在项目上配置了CORS?是的,它被配置为
AllowAnyMethod()
,然后这就是答案,CORS中间件正在处理选项请求,您的筛选器看到的是选项请求之后的GET请求。好的,我理解这一点,但情况不同,在调试日志中,我可以看到两个传入请求:Microsoft.AspNetCore.Hosting.Internal.WebHost:Information:请求启动HTTP/1.1选项http://localhost:5000/api/v1/users/33417 Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP/1.1 GEThttp://localhost:5000/api/v1/users/33417 application/json
I put操作筛选器和操作筛选器上的调试日志都会使用GET Http方法触发两次。看起来OPTIONS方法已转换为GET方法。能否在操作筛选器中检查这两个方法上的URL?我放置了一个调试日志:URL调用:http://localhost:5000/api/v1/users/33417 HTTP方法:获取URL调用:http://localhost:5000/api/v1/users/33417 HTTP方法:GET
调用相同的URL,这很奇怪。一定要在你的问题中添加这些内容。