简体   繁体   中英

ASP.NET core Cors policy

I'm having problem setting up Cors policy in my ASP.NET core project.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin() 
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddMemoryCache();
}

I've tried adding app.UseCors("AllowAll"); in Configure(IApplicationBuilder app, IHostingEnvironment env) , tried [EnableCors("AllowAll")] before controller declaration:

[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowAll")]
public class TestController : ControllerBase

and before method declaration:

[HttpPost]
[EnableCors("AllowAll")]
public JsonResult Post([FromBody] dynamic request)

and no luck, I'm keep getting "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..."

Maybe someone can help me?

I know this is too late, but can help someone,

using CorsMiddleware in specified order is matters

app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
app.UseResponseCaching();
  1. The call to UseCors must be placed after UseRouting, but before UseAuthorization.
  2. When using Response Caching Middleware, call UseCors before UseResponseCaching

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM