【问题标题】:ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resourceASP.Net Core WebAPI - 请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】: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");

不使用使用 IAsyncResourceFilterTypeFilterAttribute 也可以正常工作。

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

标签: c# asp.net-core cors


【解决方案1】:

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

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

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

【讨论】:

  • 找到了!确实有一些逻辑in the pipeline 使管道提前停止。请注意,这会检查Result != null,因此您不能将任何内容分配给Result,而Result 最初将是null,因此您也不能在其中分配任何内容。这意味着如果您希望管道继续运行,您不能影响结果。
  • 啊,我们走了!谢谢:)
猜你喜欢
  • 2013-11-29
  • 2014-07-28
  • 2014-01-19
  • 2013-12-07
相关资源
最近更新 更多