CORS In ASP.NET Core 2.0

Problem

How to implement Cross-Origin Requests (CORS) in ASP.NET Core.

Solution

Create an empty project and update the Startup to configure CORS services and middleware,

Discussion

To allow clients from a different origin to access your ASP.NET Core Web API, you’ll need to allow Cross-Origin Requests (CORS). Here same origin means clients who have identical schemes, hosts and ports.

There are two main methods of achieving this,

Using Middleware

To enable CORS for the entire Web API, you could use middleware,

  1. Add CORS services and setup named policy.
  2. Use middleware passing in policy name.

Note

The above code in the Solution section demonstrates this method.

Using MVC

To have more control over controllers and actions that enable/disable CORS, you could use attributes and filters in MVC,

  1. Add CORS services and setup named policy.
  2. To enable CORS for,

    1. Actions/Controller: Use [EnableCors]
    2. Globally: Add CorsAuthorizationFilterFactory to MVC filters. Use [DisableCors] attribute to disable CORS for individual controllers and actions.

Below code adds CORS using attributes. First configure CORS in Startup,

Then use attributes on the controller/action,

Below code adds CORS globally using MVC filters,

For information on various policy options, please refer to documentation here.

Source Code

GitHub