ASP .NET Core use multiple CORS policies
To set a default CORS policy use app.UseCors(string policyName)
overload.
Your CORS requests will be failing because you are rejecting all headers and methods. From what I read, the CORS specification states that you shouldn't set any headers at all if any of the checks fail. See implementation here, this is most likely why your client will be receiving the standard No 'Access-Control-Allow-Origin' header is present
error, as no headers are added at all, even though the Origin
check passes.
The following should work as expected, and your [EnableCors(...)]
decorator should override the default!
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("Example",
builder => builder.WithOrigins("http://www.example.com")
.AllowAnyHeader()
.AllowAnyMethod());
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc();
//other configure stuff
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowAll"); //Default
app.UseMvcWithDefaultRoute();
}
You may need to add .AllowCredentials()
to your policies, but I am not sure. Read here perhaps?
Configure Method
app.UseRouting();
app.UseCors("CorsApi");
app.UseAuthentication();
ConfigureServices method
services.AddCors(options =>
{
options.AddPolicy("CorsApi",
builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
.AllowAnyHeader()
.AllowAnyMethod());
});