I'm encountering an issue with CORS while using IAsyncResourceFilter
implementation.
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:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
});
});
And under the Configure
method:
app.UseCors("AllowAllOrigins");
It works fine without using a TypeFilterAttribute
which use IAsyncResourceFilter
.
For example calling my API action without any TypeFilterAttribute
attribute works:
public bool Get()
{
return true;
}
But when adding my TypeFilterAttribute
as follows it doesn't work and returns the error about the CORS:
[MyTypeFilterAttribute("test")]
public bool Get()
{
return true;
}
Anything I'm missing? What should I add when using IAsyncResourceFilter
?
The following is the MyTypeFilterAttribute
code: (With no real logic...)
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.
I believe you are resetting these with context.Result = new OkResult();
See poke's reply below. If you set any result in an action filter, this result gets sent back immediately, thus overwriting any other one!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With