How to enable CORS in ASP.NET Core
For ASP.NET Core 6:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
See the See the official docs for more samples.
For ASP.NET Core 3.1 and 5.0:
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.WithOrigins("http://example.com")
.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();
}
Applies to .NET Core 1 and .Net Core 2
If using .Net-Core 1.1
Unfortunately the docs are very confusing in this specific case. So I'll make it dead-simple:
-
Add
Microsoft.AspNetCore.Cors
nuget package to your project -
In
ConfigureServices
method, addservices.AddCors();
-
In
Configure
method, before callingapp.UseMvc()
andapp.UseStaticFiles()
, add:app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials());
That's it. Every client has access to your ASP.NET Core Website/API.
If using .Net-Core 2.0
-
Add
Microsoft.AspNetCore.Cors
nuget package to your project -
in
ConfigureServices
method, before callingservices.AddMvc()
, add:services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); });
-
(Important) In
Configure
method, before callingapp.UseMvc()
, addapp.UseCors("AllowAll");
"AllowAll"
is the policy name which we need to mention inapp.UseCors
. It could be any name.
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")]