【发布时间】: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。
标签: c# asp.net-core cors