.NET Core Web API CORS implementation with Angular

Updated on: May 19, 2021

To allow Cross Domain access to .NET Core Web API, we need to enable CORS in the .NET Core Web API application. Below steps show how to enable CORS in .NET Core:

Step 1: Create .NET CORE Web API Application using Visual Studio Editor or through .NET CLI:

dotnet new webapi -o CORSImplementationAPI

From Visual Studio => Create a New Project => From the template select "ASP.NET Core Web API" & click on Next => Give the project name and specify the Location & Click on Next button => Select the Target Framework & Authentication type and click on Create button to Create the .NET Core Web API application.

Step 2: Now, Create the new API Controller file(UserController) and add the below content to it:

  1. using Microsoft.AspNetCore.Cors;
  2. using Microsoft.AspNetCore.Mvc;
  3. namespace CORSImplementationAPI.Controllers
  4. {
  5.     [Route("api/[controller]")]
  6.     [ApiController]
  7.     public class UserController : ControllerBase
  8.     {
  9.         public IActionResult Get()
  10.         {
  11.             return Ok("[{\"name\": \"John\", \"age\": 25},{\"name\": \"William\", \"age\": 35}]");
  12.         }
  13.     }
  14. }

Now, if we access the Web API with URL as 'https://localhost:44377/api/User' from other domain to get the response, it gives error as:

"Access to XMLHttpRequest at 'https://localhost:44377/api/User' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Here we are trying to access API URL (https://localhost:44377/api/User) from our Angular application which is running on (http://localhost:4200), when we access the API URL from Angular application, it gives above blocked by CORS policy error.

To fix this error, we need to enable the CORS on our .NET Core Web API application, so that Cross domain can request for API access and it will work without any error. Below Steps show how to enable CORS in .NET Core Web API

Step 3: Now, run the below command to add the "Microsot.AspNetCore.Cors" Nuget Package using .NET CLI or add it using Nuget Package Manager from Visual Studio:

dotnet add package Microsoft.AspNetCore.Cors

Step 4: Now, add the below code in Startup.cs class to Add the CORS middleware:

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.DependencyInjection;
  5. namespace CORSImplementationAPI
  6. {
  7.     public class Startup
  8.     {
  9.         public Startup(IConfiguration configuration)
  10.         {
  11.             Configuration = configuration;
  12.         }
  13.         public IConfiguration Configuration { get; }
  14.         public void ConfigureServices(IServiceCollection services)
  15.         {
  16.             services.AddCors(options=>{
  17.                 options.AddPolicy("AllowMyOrigin",
  18.                 builder => builder.WithOrigins("*"));
  19.             });
  20.             services.AddControllers();
  21.         }

  22.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  23.         {
  24.             app.UseRouting();
  25.             app.UseCors("AllowMyOrigin");
  26.             app.UseAuthorization();
  27.             app.UseEndpoints(endpoints =>
  28.             {
  29.                 endpoints.MapControllers();
  30.             });
  31.         }
  32.     }
  33. }

We have added the AddCors in the ConfigureServices() method of Startup class and also added UseCors() in the Configure() method of Startup class.

Step 5: Now, we will modify the UserController.cs code, we will append the "EnableCors("AllowMyOrigin")" attribute on top of Controller definition as shown below:

  1. using Microsoft.AspNetCore.Cors;
  2. using Microsoft.AspNetCore.Mvc;
  3. namespace CORSImplementationAPI.Controllers
  4. {
  5.     [Route("api/[controller]")]
  6.     [ApiController]
  7.     [EnableCors("AllowMyOrigin")]
  8.     public class UserController : ControllerBase
  9.     {
  10.         public IActionResult Get()
  11.         {
  12.             return Ok("[{\"name\": \"John\", \"age\": 25},{\"name\": \"William\", \"age\": 35}]");
  13.         }
  14.     }
  15. }

As highlighted above, we have added [EnableCors("AllowMyOrigin")] attribute at the top of Controller, the same way you can add the  [EnableCors("AllowMyOrigin")] on the controller which you want to allow to be accessible for Cross Domains.

Below is the output of the Angular application which shows the result of .NET Core Web API on Angular application:

Code of Angular's User.service.ts file to call the .NET Core Web API from Angular:

  1. import { Injectable } from '@angular/core';
  2. import {HttpClient, HttpClientModule} from '@angular/common/http';
  3. import { UserModel } from '../Models/user-model';
  4. @Injectable({
  5.    providedIn: 'root'
  6. })
  7. export class UserService {
  8.    baseURL = 'https://localhost:44377/'
  9.    constructor(private http: HttpClient) { }
  10.    getUsers(){
  11.       return this.http.get<UserModel[]>(this.baseURL + 'api/User');
  12.    }
  13. }

Code of Angular's UserModel.ts file which is Model file to Map the .NET Core Web API's result fields with Angular fields.

  1. export class UserModel {
  2.     name: string='';
  3.     age: number=0;
  4. }

Code of Angular's app.component.ts to display the API result:

  1. import { Component, OnInit } from '@angular/core';
  2. import { UserModel } from './Models/user-model';
  3. import { UserService } from './Services/user.service';
  4. @Component({
  5.   selector: 'app-root',
  6.   templateUrl: './app.component.html',
  7.   styleUrls: ['./app.component.css']
  8. })
  9. export class AppComponent implements OnInit {
  10.   title = 'CORSImplementationApp';
  11.   userList: UserModel[]= new Array<UserModel>();
  12.   constructor(private userService: UserService){}
  13.   ngOnInit(){
  14.     this.getUsers();
  15.   }
  16.   getUsers(){
  17.     this.userService.getUsers().subscribe(result=>{
  18.       this.userList = result;
  19.     })
  20.   }
  21. }

Code of Angular's app.component.html to display the API result:

  1. <div *ngFor="let user of userList; let i=index;">
  2.   <div>{{i+1}}. Name is: {{user.name}} & Age is: {{user.age}}</div>
  3. </div>


Anguar's app.module.ts file which should be modified to add 'HttpClientModule' in the import and add it in the imports declaration as shown below:

  1. import { HttpClientModule } from '@angular/common/http';
  2. import { NgModule } from '@angular/core';
  3. import { BrowserModule } from '@angular/platform-browser';
  4. import { AppRoutingModule } from './app-routing.module';
  5. import { AppComponent } from './app.component';
  6. @NgModule({
  7.   declarations: [
  8.     AppComponent
  9.   ],
  10.   imports: [
  11.     BrowserModule,
  12.     AppRoutingModule,
  13.     HttpClientModule
  14.   ],
  15.   providers: [],
  16.   bootstrap: [AppComponent]
  17. })
  18. export class AppModule { }

You can try above code if there is a requirement to enable CORS for your .NET Core Web API.