Take advantage of the CORS middleware in ASP.NET Core to bypass the security restrictions of the web browser and allow cross-origin requests. Credit: Thinkstock 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. Launch the Visual Studio 2017 IDE. Click on File > New > Project. Select “ASP.NET Core Web Application (.NET Core)” from the list of templates displayed. Specify a name for the project. Click OK to save the project. A new window “New .NET Core Web Application…” will be displayed. Select “.NET Core” as the runtime and ASP.NET Core 2.1 (or later) from the drop-down list at the top. Select “API” as the project template. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked. We won’t be using Docker or HTTPS here. 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: Install the CORS middleware. Add the CORS middleware to the pipeline in the ConfigureServices method. Enable CORS in the Configure method. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos