Asp.net-mvc – Add ‘access-control-allow-origin’ response to options preflight request in Asp.NET

asp.netasp.net-coreasp.net-mvccors

I'm getting the following error in Chrome:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:9000' is therefore not allowed
access.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseIISPlatformHandler();

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseCors(policy => policy
       .WithOrigins("http://localhost:9000")
       .AllowAnyMethod()
       .WithHeaders("Access-Control-Allow-Origin, Content-Type, x-xsrf-token, Authorization")
       .AllowCredentials());

    app.UseMvc();
}

According to chrome there is not a single header being added to the response.

What is the correct way to add the access-control-allow-origin header to a options response in Asp.NET 5?

Best Answer

Consider that Google Chrome has an issue which does not support localhost to go through the Access-Control-Allow-Origin.

In your code, you have enabled CORS with the AddCors and UseCors methods in Configure method, please make sure you've followed the instructions available in Specifying a CORS Policy (which is used in ConfigureServices method) and How to enable CORS in ASP.NET 5

You can also simply write an Action Filter for plain Asp.net MVC controller.

Types of CORS'

  1. Microsoft.AspNet.WebApi.Cors : use it to enable the CORS request ONLY for the Web APIs.
  2. Microsoft.AspNet.Cors : Use it to enable CORS for MVC controllers.
  3. Microsoft.Owin.Cors : Use it to enable CORS for all cross-origins requests coming to your site, for example, when you you want to enable CORS for both Web API and SignalR.