ASP.Net核心WebAPI - No' Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2017-04-30 09:07:30

标签: c# asp.net-core cors

在使用 IAsyncResourceFilter 实施时,我遇到了CORS问题。 我希望能够从其他领域调用我的行动......

我已在Startup文件下定义了CORS策略,如下所示:

services.AddCors(options =>
{
    options.AddPolicy("AllowAllOrigins",
    builder =>
    {
        builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
    });
});

Configure方法下:

app.UseCors("AllowAllOrigins");

如果不使用 TypeFilterAttribute 使用 IAsyncResourceFilter ,它可以正常工作。

例如,在没有任何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;
    }
}

1 个答案:

答案 0 :(得分:4)

Cors中间件在响应结果对象上设置标头。

我相信您正在使用context.Result = new OkResult();

重置这些内容

请参阅下面的poke回复。如果在动作过滤器中设置任何结果,则会立即将此结果发回,从而覆盖任何其他结果!