.NET Core Web API CORS implementation with Angular
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:
- using Microsoft.AspNetCore.Cors;
- using Microsoft.AspNetCore.Mvc;
- namespace CORSImplementationAPI.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class UserController : ControllerBase
- {
- public IActionResult Get()
- {
- return Ok("[{\"name\": \"John\", \"age\": 25},{\"name\": \"William\", \"age\": 35}]");
- }
- }
- }
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:
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- namespace CORSImplementationAPI
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddCors(options=>{
- options.AddPolicy("AllowMyOrigin",
- builder => builder.WithOrigins("*"));
- });
- services.AddControllers();
- }
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
- app.UseCors("AllowMyOrigin");
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
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:
- using Microsoft.AspNetCore.Cors;
- using Microsoft.AspNetCore.Mvc;
- namespace CORSImplementationAPI.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- [EnableCors("AllowMyOrigin")]
- public class UserController : ControllerBase
- {
- public IActionResult Get()
- {
- return Ok("[{\"name\": \"John\", \"age\": 25},{\"name\": \"William\", \"age\": 35}]");
- }
- }
- }
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:
- import { Injectable } from '@angular/core';
- import {HttpClient, HttpClientModule} from '@angular/common/http';
- import { UserModel } from '../Models/user-model';
- @Injectable({
- providedIn: 'root'
- })
- export class UserService {
- baseURL = 'https://localhost:44377/'
- constructor(private http: HttpClient) { }
- getUsers(){
- return this.http.get<UserModel[]>(this.baseURL + 'api/User');
- }
- }
Code of Angular's UserModel.ts file which is Model file to Map the .NET Core Web API's result fields with Angular fields.
- export class UserModel {
- name: string='';
- age: number=0;
- }
Code of Angular's app.component.ts to display the API result:
- import { Component, OnInit } from '@angular/core';
- import { UserModel } from './Models/user-model';
- import { UserService } from './Services/user.service';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent implements OnInit {
- title = 'CORSImplementationApp';
- userList: UserModel[]= new Array<UserModel>();
- constructor(private userService: UserService){}
- ngOnInit(){
- this.getUsers();
- }
- getUsers(){
- this.userService.getUsers().subscribe(result=>{
- this.userList = result;
- })
- }
- }
Code of Angular's app.component.html to display the API result:
- <div *ngFor="let user of userList; let i=index;">
- <div>{{i+1}}. Name is: {{user.name}} & Age is: {{user.age}}</div>
- </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:
- import { HttpClientModule } from '@angular/common/http';
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- HttpClientModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
You can try above code if there is a requirement to enable CORS for your .NET Core Web API.