[英]ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm encountering an issue with CORS while using IAsyncResourceFilter
implementation. 在使用
IAsyncResourceFilter
实现时,我遇到了CORS的问题。 I want to be able to call my actions from other domains as well... 我希望能够从其他领域调用我的行为......
I've defined the CORS policy under my Startup
file as the following: 我在我的
Startup
文件下定义了CORS策略,如下所示:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
});
});
And under the Configure
method: 并在
Configure
方法下:
app.UseCors("AllowAllOrigins");
It works fine without using a TypeFilterAttribute
which use IAsyncResourceFilter
. 它不使用使用
IAsyncResourceFilter
的TypeFilterAttribute
就可以正常工作。
For example calling my API action without any TypeFilterAttribute
attribute works: 例如,在没有任何
TypeFilterAttribute
属性的情况下调用我的API操作有效:
public bool Get()
{
return true;
}
But when adding my TypeFilterAttribute
as follows it doesn't work and returns the error about the CORS: 但是当按如下方式添加我的
TypeFilterAttribute
,它不起作用并返回有关CORS的错误:
[MyTypeFilterAttribute("test")]
public bool Get()
{
return true;
}
Anything I'm missing? 我缺少什么? What should I add when using
IAsyncResourceFilter
? 使用
IAsyncResourceFilter
时我应该添加什么?
The following is the MyTypeFilterAttribute
code: (With no real logic...) 以下是
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;
}
}
Cors middleware sets headers on the response result object. Cors中间件在响应结果对象上设置标头。
I believe you are resetting these with context.Result = new OkResult();
我相信你正在使用
context.Result = new OkResult();
重置这些context.Result = new OkResult();
See poke's reply below. 请参阅下面的poke的回复。 If you set any result in an action filter, this result gets sent back immediately, thus overwriting any other one!
如果在动作过滤器中设置任何结果,则会立即将此结果发回,从而覆盖任何其他结果!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.