ASP.Net Core WebAPI - 请求的资源上不存在“Access-Control-Allow-Origin”标头
Posted
技术标签:
【中文标题】ASP.Net Core WebAPI - 请求的资源上不存在“Access-Control-Allow-Origin”标头【英文标题】:ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource 【发布时间】:2017-09-28 00:29:32 【问题描述】:我在使用 IAsyncResourceFilter
实现时遇到了 CORS 问题。
我也希望能够从其他域调用我的操作...
我在 Startup
文件下定义了 CORS 策略,如下所示:
services.AddCors(options =>
options.AddPolicy("AllowAllOrigins",
builder =>
builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
);
);
在Configure
方法下:
app.UseCors("AllowAllOrigins");
不使用使用 IAsyncResourceFilter
的 TypeFilterAttribute
也可以正常工作。
例如在没有任何TypeFilterAttribute
属性的情况下调用我的 API 操作:
public bool Get()
return true;
但是当按如下方式添加我的TypeFilterAttribute
时,它不起作用并返回有关 CORS 的错误:
[MyTypeFilterAttribute("test")]
public bool Get()
return true;
我缺少什么吗?使用IAsyncResourceFilter
时应该添加什么?
以下是MyTypeFilterAttribute
的代码:(没有真正的逻辑……)
public class MyTypeFilterAttribute : TypeFilterAttribute
public MyTypeFilterAttribute(params string[] name) : base(typeof(MyTypeFilterAttributeImpl))
Arguments = new[] new MyTypeRequirement(name) ;
private class MyTypeFilterAttributeImpl: Attribute, IAsyncResourceFilter
private readonly MyTypeRequirement_myTypeRequirement;
public MyTypeFilterAttributeImpl(MyTypeRequirement myTypeRequirement)
_myTypeRequirement= myTypeRequirement;
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
context.Result = new OkResult();
await next();
public class MyTypeRequirement : IAuthorizationRequirement
public string Name get;
public MyTypeRequirement(string name)
Name = name;
【问题讨论】:
Ehm...发布类型过滤器的内容怎么样? 添加了代码。谢谢 在方法中添加[EnableCors("AllowAllOrigins")]
属性是否有效?
这个context.Result = new OkResult();
不只是清除任何标题集吗?
@Mardoxx 那应该是only set the status code。
【参考方案1】:
Cors 中间件在响应结果对象上设置标头。
我相信你正在使用context.Result = new OkResult();
重置这些
请参阅下面 poke 的回复。如果您在操作过滤器中设置任何结果,该结果会立即被发回,从而覆盖任何其他结果!
【讨论】:
找到了!确实有一些逻辑in the pipeline 使管道提前停止。请注意,这会检查Result != null
,因此您不能将任何内容分配给Result
,而Result
最初将是null
,因此您也不能在其中分配任何内容。这意味着如果您希望管道继续运行,您不能影响结果。
啊,我们走了!谢谢:)以上是关于ASP.Net Core WebAPI - 请求的资源上不存在“Access-Control-Allow-Origin”标头的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core HttpClient 请求在 webapi 返回 406 时返回 200
asp.net core webapi Post接收不到ajax请求数据
本地 Javascript Fetch Post 请求失败,调用 ASP.NET Core 2.2 Web API。 CORS 已启用
如何在 Asp Net Core Web App(不是 WebAPI)中存储令牌