Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource

Tags:

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;
    }
}
like image 424
Tomer Peled Avatar asked Apr 30 '17 09:04

Tomer Peled


1 Answers

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!

like image 85
Mardoxx Avatar answered Sep 23 '22 10:09

Mardoxx