Enabling CORS In ASP.NET Core Web API

Enabling Cross-Origin Request(CORS) in Asp.Net Core Applications.

 Asp.Net Core   
 

Posted: August 14, 2019. | By: mustafa

 EnablingCorsinAsp.NetCoreWebAPI.png, Asp.Net Core, WEB API2, Asp.Net Core, CORS,

What is a Cross-Origin Request OR CORS?

Cross-Origin Resource Sharing (CORS) manages the cross-origin requests. CORS allows us to make the request from one server to another or across different domains and client applications.

Today I am going to explain how we can allow Cross-Origin Request into our Asp.Net Core Web Api.
First let us install the CORS nuget package using the visual studio package manager console while runing the command.

Install-Package Microsoft.AspNetCore.Cors

Open the Asp.Net Core application and go to startup.cs in application root folder.

We have two method ConfigureServices() and Configure() in Startup.cs file. In the ConfigureServices method of your startup.cs, add the CORS services.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Make sure you call this previous to AddMvc
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

 

Add UseCors in Configure() method.

app.UseCors(builder => builder
 .AllowAnyOrigin()
 .AllowAnyMethod()
 .AllowAnyHeader()
 .AllowCredentials()); 
 app.UseMvc();

 

Please add method app.UseCors, before app.UseMvc() in Configure method.

Make sure you declare the CORS functionality before MVC so the middleware fires before the MVC pipeline gets control and terminates the request.

 Now hit the F5 and run the application and test whether we are able to test our endpoint from another application or different domain.


related posts

Back to top