I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.
The EnableCors
attribute accepts policyName
Based on Henk's answer I have been able to come up with the specific domain, the method I want to allow and also the header I want to enable CORS for:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
.WithMethods("GET")
.WithHeaders("name")));
services.AddMvc();
}
usage:
[EnableCors("AllowSpecific")]
Specifically in dotnet core 2.2 with SignalR you must change
.WithOrigins("http://localhost:3000")
or
.SetIsOriginAllowed(isOriginAllowed: _ => true) //for all origins
instead .AllowAnyOrigin()
with .AllowCredentials()
https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/
https://github.com/aspnet/AspNetCore/issues/4483
In case you get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." Specifically for PUT and DELETE requests, you could try to disable WebDAV on IIS.
Apparently, the WebDAVModule is enabled by default and is disabling PUT and DELETE requests by default.
To disable the WebDAVModule, add this to your web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
});
}
You have to configure in Startup.cs class
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
You have to configure a CORS policy at application startup in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ...
}
The CorsPolicyBuilder
in builder
allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:
[EnableCors("MyPolicy")]
Or apply it to every request:
public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");
// ...
// This should always be called last to ensure that
// middleware is registered in the correct order.
app.UseMvc();
}