How to configure CORS in .NET Core

Alex Maher
3 min readJan 21, 2023

--

Introduction

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers that blocks web pages from making requests to a different domain than the one that served the web page. This is done to prevent malicious websites from making unauthorized requests on behalf of the user.

It is important for .NET Core API because it allows web applications on different domains to consume the API. Without CORS, the browser would block the request and the API would not be accessible to the web application.

While CORS is an important security feature, it does not provide complete security for your .NET Core API. It does not prevent unauthorized access to the API or protect against common web application attacks such as cross-site scripting (XSS) or cross-site request forgery (CSRF). Therefore, it is important to use other security measures such as authentication, authorization, and input validation to secure your API.

Configuration

Here is an example of how to configure CORS for an ASP.NET Core API:

Install the Microsoft.AspNetCore.Cors package by running the following command in the Package Manager Console:

Install-Package Microsoft.AspNetCore.Cors

In the Startup.cs file, add the following line to the ConfigureServices method to enable CORS:

services.AddCors();

The above is a very basic example, but you can configure CORS policies using the AddCors method. Here are some examples:

Allow any origin, method, and header:

services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});

This configuration allows any origin, method, and header to access resources on the server. It’s the most permissive option, but also the least secure.

Allow specific origin, method and headers:

services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("http://example.com")
.WithMethods("GET", "POST")
.WithHeaders("content-type", "accept");
});
});

This configuration allows only GET and POST requests with the headers content-type and accept from the origin http://example.com. This is more restrictive than the previous example, but also more secure.

Allow specific origin, method and headers for specific routes:

services.AddCors(options =>
{
options.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("http://example.com")
.WithMethods("GET")
.WithHeaders("content-type")
.WithExposedHeaders("content-type");
});
});

This configuration allows only GET requests with the headers content-type from the origin http://example.com. Also it allows the content-type headers to be exposed to the client. This policy can be applied to specific routes or controllers using the [EnableCors("MyPolicy")] attribute.

Apply CORS

In the Configure method, you can use the UseCors method to apply the policies that were defined earlier, this can be done in a couple of ways:

Apply a global CORS policy to the entire application:

app.UseCors(options => 
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

This configuration allows any origin, method, and header to access resources on the server. This is useful when you want to apply a single set of CORS rules to your entire application.

Apply a specific policy that was defined previously:

app.UseCors("MyPolicy");

This configuration applies the “MyPolicy” policy that was previously defined using AddCors method to the entire application.

Apply CORS policy to specific routes:

This configuration applies the “MyPolicy” policy that was previously defined using the AddCors method only to requests that start with /api. This allows you to apply different CORS rules to different parts of your application, based on the route.

You can also use UseCors method in conjunction with app.UseEndpoints(...) to apply the policy to specific endpoints

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("MyPolicy");
});

Important

It’s important to note that the UseCors method should be called after the UseRouting and before the UseEndpoints methods in the Configure method of the Startup.cs file, in order to ensure that the CORS policy is applied before any endpoints are executed.

Extra

In addition to configuring CORS in the Startup.cs file, you can also configure CORS in the appsettings.json file.

{
"Cors": {
"AllowedOrigins": "http://example.com,https://example.com",
"AllowedMethods": "GET,POST",
"AllowedHeaders": "content-type,accept"
}
}

In this example, the CORS policy allows only GET and POST requests with the headers content-type and accept from the origins http://example.com and https://example.com.

You can then load these settings in your Startup.cs file and configure the CORS using these settings:

var corsOptions = Configuration.GetSection("Cors").Get<CorsOptions>();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins(corsOptions.AllowedOrigins)
.WithMethods(corsOptions.AllowedMethods)
.WithHeaders(corsOptions.AllowedHeaders);
});
});

You can also create a class CorsOptions to store these settings and use it in configuration

public class CorsOptions
{
public string AllowedOrigins { get; set; }
public string AllowedMethods { get; set; }
public string AllowedHeaders { get; set; }
}

You can also use UseCors method in conjunction with this configuration in the same way as explained before.

Thank you for reading, I hope this guide was helpful in understanding how to configure CORS in .NET Core. If you have any questions or need further clarification, please don’t hesitate to ask.

--

--

Alex Maher
Alex Maher

Written by Alex Maher

.NET C# dev with 10+ yrs exp, self-taught & passionate web developer. Sharing tips & experiences in C# and web dev.

No responses yet