ASP.Net核心WebAPI - 请求的资源上没有"Access-Control-Allow-Origin"标头

Tom*_*led 5 c# cors asp.net-core

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

我在我的Startup文件中定义了CORS策略如下:

services.AddCors(options =>
{
    options.AddPolicy("AllowAllOrigins",
    builder =>
    {
        builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
    });
});
Run Code Online (Sandbox Code Playgroud)

并根据Configure方法:

app.UseCors("AllowAllOrigins");
Run Code Online (Sandbox Code Playgroud)

没有使用TypeFilterAttribute哪种用途它工作正常IAsyncResourceFilter.

例如,在没有任何TypeFilterAttribute属性的情况下调用我的API操作:

public bool Get()
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

但是当添加我的TypeFilterAttribute如下它不起作用并返回有关CORS的错误:

[MyTypeFilterAttribute("test")]
public bool Get()
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

我缺少什么?使用时应该添加什么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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*oxx 4

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

我相信你正在重置这些context.Result = new OkResult();

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

  • 找到了![管道中](https://github.com/aspnet/Mvc/blob/rel/1.1.1/src/Microsoft.AspNetCore.Mvc.Core/Internal/ControllerActionInvoker.cs#L399)确实存在一些逻辑使管道提早停止。请注意,这会检查 `Result != null`,因此您无法将任何内容分配给 `Result`,并且 `Result` 最初将为 `null`,因此您也无法在其中分配任何内容。这意味着如果您希望管道继续运行,则不能影响结果。 (4认同)