Configuring Cors Policy in .net core

Tuesday, November 20, 2018

By: Chris Dunn

To allow sharing responses cross-origin and allow for more versatile fetches than possible with HTML’s form element, the CORS protocol exists. It is layered on top of HTTP and allows responses to declare they can be shared with other origins. Source

They is a lot more in depth information on CORS than I could provide here in my post so I will rely on others if you are unfamiliar with what it's all about. See a good explanation from Mozilla. My goal for this post it to show you how to configure a basic setup in .net core.

Configuration

To configure CORS we start by registering the CORS service in the ConfigureServices method of Startup. At this point we will also define the CORS policy we will be using.  You can have more than one policy and assign each to different controllers and actions independently.

For my example I am specifying the acceptable origin from which a call can be made, a local server for an Angular application. Instead of WithOrigins I could specify AllowAllOrigins to enable a client to make calls from any origin.  Unless your product is an API used by developers who build clients, you're better off being specific.

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200"));
});
services.AddMVC();
}

I have a number of other options I can tack on to the policy like specifying only certain headers (WithHeaders, AllowAnyHeaders), methods (WithMethods, AllowAnyMethods) or credentials (AllowCredentials). But I won't go into those now.

After we've registered Cors and configured our policy. We have two options for enabling Cors in our application. First, we can enable it via MVC by adding the EnableCors attribute to controllers and actions.

[EnableCors("CorsPolicy")]
public class ValuesController: Controller {}

The other option is to enable it globally by adding Cors and the policy to the middleware request pipeline. As a parameter of the call we need to specify the Cors Policy we defined in our AddCors command in the ConfigureServices method. UseCors needs to be called before UseMVC.

public void Configure(IApplicationBuilder app)
{
app.UseCors("CorsPolicy");
app.UseMVC();
}

 

Tags: c# cors .net core

Copyright 2019 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.