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:
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)
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With