How to enable CORS in ASP.NET Core (2024)

.NET Programming

By Joydip Kanjilal, Contributor, InfoWorld |

Take advantage of the CORS middleware in ASP.NET Core to bypass the security restrictions of the web browser and allow cross-origin requests.

How to enable CORS in ASP.NET Core (2)

The same-origin policy is a standard security mechanism in web browsers that allows communications between two URLs only if they share the same origin, meaning the same protocol, port, and host. For example, a client or script at http://localhost:6000 will not be able to access a server application at http://localhost:5080 because these two URLs have different port addresses. Security restrictions in your web browser will not allow requests to a server application in another domain.

Here is where CORS (Cross-Origin Resource Sharing) comes to the rescue. CORS is a W3C standard that allows you to get around the default same-origin policy adopted by the browsers. In short, you can use CORS to allow some cross-origin requests while preventing others. In this article we’ll examine how CORS can be enabled and configured in ASP.NET Core.

Create an ASP.NET Core Web API project in Visual Studio 2017

First off, let’s create an ASP.NET Core Web API project in Visual Studio. If Visual Studio 2017 is up and running in your system, follow the steps outlined below to create an ASP.NET Core Web API project.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.NET Core Web Application (.NET Core)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. A new window “New .NET Core Web Application…” will be displayed.
  7. Select “.NET Core” as the runtime and ASP.NET Core 2.1 (or later) from the drop-down list at the top.
  8. Select “API” as the project template.
  9. Ensure that the check boxes "Enable Docker Support" and “Configure for HTTPS” are unchecked. We won’t be using Docker or HTTPS here.
  10. Ensure that “No Authentication” is selected as we won’t be using authentication either.

This will create a new ASP.NET Core project in Visual Studio. We’ll use this project to enable and configure CORS in the sections that follow. Let’s call this project the server application. You can now create another .NET Core Web Appication project in Visual Studio to serve as the client application.

Note that if you try to access the controller methods of the server application from the client application by making AJAX calls, you’ll see that the web browser rejects the request. This is because CORS isn’t enabled in the server application.

Add CORS to the ASP.NET Core request processing pipeline

To work with CORS in ASP.NET Core, these are the steps we need to follow:

  1. Install the CORS middleware.
  2. Add the CORS middleware to the pipeline in the ConfigureServices method.
  3. Enable CORS in the Configure method.
  4. Enable CORS in the controllers, the action methods, or globally.

The Microsoft.AspNetCore.Cors package is the CORS middleware that can be leveraged in ASP.NET Core to enable cross-origin resource sharing. To install this package, click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution. Then search for theMicrosoft.AspNetCore.Cors package in the NuGet package manager and install it. As of this writing, the latest stable version of the Microsoft.AspNetCore.Cors package is 2.2.0.

Next, add the cross-origin resource sharing services to the pipeline. To do this, invoke the AddCors method on the IServiceCollection instance in the ConfigureServices method of the Startup class as shown in the code snippet below.

public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

Configure CORS policy in ASP.NET Core

You can configure CORS policy in various ways in ASP.NET Core. As an example, the following code snippet allows only a specific origin to be accessed.

services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:60571"));
});

Apart from the WithOrigins method, ASP.NET gives us a number of other methods related to other policy options. These include the following:

  • AllowAnyOrigin — used to allow access to the resource from any origin
  • AllowAnyHeader— used to allow all HTTP headers in the request
  • AllowAnyMethod— used to allow any HTTP methods to be accessed
  • AllowCredentials — used to pass credentials with the cross-origin request
  • WithMethods — used to allow access to specific HTTP methods only
  • WithHeaders — used to allow access to specific headers only

If you want to allow more than one origin to access a resource, you can specify the following in the ConfigureServices method.

services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:60571", "http://localhost:60890"));
});

If you want to allow any origin to access a resource, you should use the AllowAnyOrigin method instead of the WithOrigins method. The code snippet given below illustrates how you can allow CORS requests from all origins with any scheme.

services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder => builder.AllowAnyOrigin());
});

CORS is a useful mechanism that allows us to flexibly bypass the restrictions of the same-origin policy of web browsers. When we want to allow cross-origin access to our server applications, we can use CORS middleware in ASP.NET Core to do so while taking advantage of a variety of cross-origin access policies.

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023

Related:

  • Microsoft .NET
  • C#
  • Web Development
  • Software Development

Joydip Kanjilal is a Microsoft MVP in ASP.NET, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .NET and related technologies.

Follow

Copyright © 2018 IDG Communications, Inc.

How to enable CORS in ASP.NET Core (2024)
Top Articles
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 5689

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.