I am trying to enable CORS in .NET Core in this way:
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
However, when I am sending a request to my app with Angular 2 I am getting the famous
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
error message.
I am also using Windows Authentication + WebListener. If I am checking with postman the only response headers are:
Content-Length →3533 Content-Type →application/json; charset=utf-8 Date →Fri, 14 Oct 2016 12:17:57 GMT Server →Microsoft-HTTPAPI/2.0
So there must be still something wrong configured. Any proposals?
If I remove the outcommented line it works, but I need Windows Authentication :-(
var host = new WebHostBuilder()
.UseWebListener()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
//.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
.Build();
Assume you have the answer, but for the benefit of searchers, I had the same problem with the standard tutorial on .NET Core Cors.
One of the many errors encountered:
After playing around, the following code worked. Full class posted below to aid understanding of what goes where.
To use it you can add the
EnableCorsAttribute
either on the controller or on the method. e.g.or
When I called this using the following code (using standard js/jQuery for easy of copy and paste), the communication stopped being rejected.
In ASPNET CORE 2.0, The following works for me
This way works normally, just tried it on angular2 with .net core. The issue the OP is having is that this doesnt work with windows authentication. I am assuming the middleware for windows authentication is happening before a request comes through, in which case its breaking. Best bet would be to see if there is a way to enable the windows auth middleware after the cors middleware has processed in Configure.
Then the order would be
App.UseCors()
App.UseWindowsAuth()
App.UseMVC()
They must happen in this order for it to work.
What the documentation misses, is the importance of .AllowAnyMethod(). If not present, the dreaded No 'Access-Control-Allow-Origin' will keep bugging you. In your code it's there, so I guess you missed setting the right header in jour client side application.
I Personally got it to work by allowing all:
And my Angular post function like:
After that, you gradually work your way up by specifying origins etc.
The answer of @HockeyJ is right, but you can do something more concise if wanted.