Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 'access-control-allow-origin' response to options preflight request in Asp.NET

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?

like image 979
Jamesla Avatar asked Dec 03 '15 21:12

Jamesla


People also ask

How do you add the Access-Control allow Origin header to the response?

Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");

How do you fix CORS missing Allow origin?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.


1 Answers

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.
like image 156
Amirhossein Mehrvarzi Avatar answered Oct 20 '22 12:10

Amirhossein Mehrvarzi