How do I enable CORS in ASP.NET Core?

Posted: (EET/GMT+2)

 

Cross-Origin Resource Sharing (CORS) in modern browsers allows a browser to call your API from a different origin. Here, the term "origin" basically refersh to the URL from which the front-end application loads, and the URL in which the backend API to call resides. If they are different ("a different origin"), then CORS settings must be set at the backend.

In ASP.NET Core, enabling CORS is straightforward and is done in two steps: register a policy in "ConfigureServices" method, and then apply it in the HTTP pipeline.

First, define a named CORS policy:

// Startup.cs (ASP.NET Core 2.0)
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyCors", builder =>
            builder.WithOrigins("https://example.com")
                   .AllowAnyHeader()
                   .AllowAnyMethod());
    });

    services.AddMvc();
}

Then, enable the policy in the pipeline:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("MyCors");
    app.UseMvc();
}

If you want to allow credentials (cookies, auth headers), remember that "AllowCredentials()" cannot be combined with "AllowAnyOrigin()". Instead, you must specify explicit origins. For quick local testing, you can temporarily use ".AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()", but for production, prefer a restricted list of origins.

You can also apply CORS at the controller or action level with the [EnableCors("MyCors")] attribute. Keeping CORS explicit and policy-based helps avoid surprises when frontends and APIs are deployed under different hostnames.