Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5/Core/vNext CORS not working even if allowing pretty much everything

I have a ASP.NET 5 Web API (Well, MVC now anyway) back-end which I am consuming in with the axios library in my JS app.

My CORS config in MVC is the following:

public void ConfigureServices(IServiceCollection services)
{
      services.AddMvc();
      services.AddCors();
} 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ 
      app.UseCors(builder => {
          builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
      });
}

So in other words, I should be allowing every request possible. However, while this fixed preflight requests, a POST requests still gets rejected (I can see it executes on the server, but there's no header in the response so it results in a client side error).

Does anyone have any ideas why this wouldn't work ?

These are the headers that are returned by the MVC api:

  • For the OPTIONS preflight (this one passes): OPTIONS response
  • For the actual POST request (this one does NOT pass): POST response
like image 733
valorl Avatar asked May 10 '16 12:05

valorl


3 Answers

You have to add Cors before MVC. The registration order of the middleware is important. If Cors is registered after mvc it will never be called. They are called in the order of registration.

Once cors process the request, it will pass it to next middleware (Mvc)

like image 91
Tseng Avatar answered Oct 26 '22 01:10

Tseng


@Norgerman mentioned this in the comments, but I think it is worthy of an answer because I've made this mistake myself several times:

The CORS middleware only works on actual cross-domain requests

It is not fired if you just access a same domain request like typing a URL into the browser.

This means if you are testing you have to either use an actual cross-domain request from an XHR client on another port or domain, or an HTTP client that can explicitly poke an origin header into the HTTP request.

like image 30
Rick Strahl Avatar answered Oct 26 '22 00:10

Rick Strahl


The problem was actually in the fact that there was an exception in the action processing the POST request and as Norgerman mentioned, the default exception handler cleared the CORS headers.

like image 11
valorl Avatar answered Oct 26 '22 02:10

valorl