Search code examples
c#asp.net-corecors

How to enable CORS in ASP.NET Core


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 of type string as parameter:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

What does the policyName mean and how can I configure CORS on an ASP.NET Core Web API?


Solution

  • 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 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();
    }