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:
Assuming that you are trying to create a truly PUBLIC endpoint, this worked for me:
Make sure that this:
app.UseCors(builder => {
builder.AllowAnyOrigin()
builder.AllowAnyMethod()
builder.AllowAnyHeader()
});
Occurs before any of these:
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCookiePolicy();
app.useMvc();
Remember, we are dealing with a "pipeline". The cors stuff has to be first.
Also - (again, I'm assuming, "public endpoint") - make sure that your XHR call has... xhr.withCredentials = false;
... or just omit it. If you have it set to "true", you will get a CORS warning about the "Wildcard".
For me helps this:
services.AddCors(options =>{
options.AddPolicy(AllowAllCorsPolicy, builder =>{
builder
.SetIsOriginAllowed(x =>_ = true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Taken from .
@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.
This works for me:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
}
Please notice that Windows Firewall and project's .vs\config\applicationhost.config
must be properly set up besides enabling CORS in your project. The checklist below can help:
Is the port used by your application/API open in the firewall? If not, open it.
Open your project .vs\config\applicationhost.config
file and search for <binding protocol="http" bindingInformation="*:NNNNN:localhost" />
(where NNNNN is the number of the IP port used by your application/API). Add a second line after that, <binding protocol="http" bindingInformation="*:NNNNN:*" />
, so you allow any IP address to access your application.
Restart IIS Express and remember that running Visual Studio as Administrator is important most of times.
After that, continue your CORS set up and testing.
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.