Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS in ASP.NET Core

People also ask

What is CORS in .NET core Web API?

In this article This article shows how to enable CORS in an ASP.NET Core app. Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy.

How do I add a CORS policy to .NET Core 6?

Enabling CORS in ASP.NET Core with Attributes We can use just the [EnableCors] attribute on top of the controller or the action, and it will implement a default CORS policy. Or we can use the [EnableCors("Policy name")] attribute, to apply a named CORS policy.


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, add services.AddCors();

  • In Configure method, before calling app.UseMvc() and app.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 calling services.AddMvc(), add:

      services.AddCors(options =>
         {
             options.AddPolicy("AllowAll",
                 builder =>
                 {
                     builder
                     .AllowAnyOrigin() 
                     .AllowAnyMethod()
                     .AllowAnyHeader()
                     .AllowCredentials();
                 });
         });
    
  • (Important) In Configure method, before calling app.UseMvc(), add app.UseCors("AllowAll");

    "AllowAll" is the policy name which we need to mention in app.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")]

Got this working with .NET Core 3.1 as follows

  1. Make sure you place the UseCors code between app.UseRouting(); and app.UseAuthentication();
app.UseHttpsRedirection();

app.UseRouting();
app.UseCors("CorsApi");

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
    endpoints.MapControllers();
});
  1. Then place this code in the ConfigureServices method
services.AddCors(options =>
{
    options.AddPolicy("CorsApi",
        builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
            .AllowAnyHeader()
            .AllowAnyMethod());
});
  1. And above the base controller I placed this
[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

Now all my controllers will inherit from the BaseController and will have CORS enabled


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