ASPAP Core WebAPI Header - No header "Access-Control-Allow-Origin" is present on the requested resource

I am encountering a problem with CORS when using IAsyncResourceFilter . I also want to be able to call my actions from other domains ...

I defined the CORS policy in my Startup file as follows:

 services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin(); }); }); 

And under the Configure method:

 app.UseCors("AllowAllOrigins"); 

It works great without using TypeFilterAttribute , which use IAsyncResourceFilter .

For example, calling my API action without using the TypeFilterAttribute attribute:

 public bool Get() { return true; } 

But when adding my TypeFilterAttribute , as shown below, it does not work and returns an error about CORS:

 [MyTypeFilterAttribute("test")] public bool Get() { return true; } 

Anything I miss? What should I add when using IAsyncResourceFilter ?

The following is the code for MyTypeFilterAttribute : (Without 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; } } 
+5
source share
1 answer

The Cors binding tool sets headers in the response result object.

I believe that you reset them using context.Result = new OkResult();

See the answer to the question below. If you set any result in the action filter, this result will be immediately sent back, thus overwriting any other!

+4
source

Source: https://habr.com/ru/post/1267328/


All Articles