Enable CORS (2), Consume Web API By Angular Client

This article is the second part of the previous article 《Enable CORS (1), Consume Web API By MVC In .NET Core》. We will make another Web API consumer, an Angular client, and show the effect of the CORS issue.


In the previous articles, we created a ASP.NET Core MVC app and associated a Web API service. In Part I, we made a MVC app as a client to consume Web API in the same app (origin)  and in Part II, and we made a separated Web API server and consumed it by a ASP.NET MVC Client in .NET Core in a different app (origin) in Part III.
In this article, before we demonstrate the CORS to be enabled, we will make another Web API client by Angular.  We can see the same SORS issue here. We will make three parts in this article:
  • Build a simple Angular app to consume ag-grid data;
  • Use the Angular app to consume our previous built Web API with different origin;
  • Use the Angular app to consume our previous built Web API in the same origin, and see the difference compared to the above;

A - Build an Angular app to Consume ag-Grid data:

We borrow ag-Grid as a test sample to build up a Grid consuming data remotely,
  • Step 1: Create an Angular application;
  • Step 2: Add the ag-Grid NPM packages;
  • Step 3,:Add the ag-Grid styles;
  • Step 4: Update Module;
  • Step 5: Update Component;
  • Step 6: Update Template;
  • Step 7: Run and Test app
Step 1 - Create an Angular application
We use the Angular CLI to create projects,
  1. npm install -g @angular/cli                      // Install the Angular CLI  
  2. ng new ag-Grid --style scss --routing false      // Creat a new Angular app  
  3. cd ag-Grid                                       // change to the app directory  
  4. ng serve --open                                  // Run the app    
The app will run like this,
Step 2 - Add the ag-Grid NPM packages
We use the Angular CLI
  1. npm install --save ag-grid-community ag-grid-angular    
  2. npm install     
  3. npm install --save ag-grid-enterprise   
Step 3 - Add the ag-Grid styles
Replace the content of src/styles.scss with the following code,
  1. @import "../node_modules/ag-grid-community/src/styles/ag-grid.scss";  
  2. @import "../node_modules/ag-grid-community/src/styles/ag-theme-alpine/sass/ag-theme-alpine-mixin.scss";  
  4. .ag-theme-alpine {  
  5.     @include ag-theme-alpine((  
  6.         odd-row-background-color: #CFD8DC  
  7.     ));  
Step 4 - Update Module
Replace the content of src/app/module.ts with the following code,
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  4. import { AppComponent } from './app.component';  
  5. import { AgGridModule } from 'ag-grid-angular';  // ag-grid  
  6. import { HttpClientModule } from '@angular/common/http'// remote  
  8. @NgModule({  
  9.   declarations: [AppComponent],  
  10.   imports: [  
  11.     BrowserModule,  
  12.     HttpClientModule, // remote  
  13.     AgGridModule.withComponents([])  // ag-grid  
  14.   ],  
  15.   providers: [],  
  16.   bootstrap: [AppComponent]  
  17. })  
  18. export class AppModule {} 
Step 5 - Update Component
Replace the content of src/app/app.component.ts with the following code (the blue highlited parts will be replaced later when we use our developed Web API as server), 
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http'// remote  
  4. import { AgGridAngular } from 'ag-grid-angular';  
  5. import 'ag-grid-enterprise';  
  7. @Component({  
  8.     selector: 'app-root',  
  9.     templateUrl: './app.component.html',  
  10.     styleUrls: ['./app.component.scss']  
  11. })  
  12. export class AppComponent {  
  13.     @ViewChild('agGrid') agGrid: AgGridAngular;  
  14.     title = 'ag-Grid';  
  16.     columnDefs = [  
  17.       { field: 'make', sortable: true, filter: true },  
  18.       { field: 'model', sortable: true, filter: true },  
  19.       { field: 'price', sortable: true, filter: true }  
  20.   ];  
  22.   rowData: any;  
  24.   constructor(private http: HttpClient) {  
  26.   }  
  28.   ngOnInit() {       
  29.       this.rowData = this.http.get('https://www.ag-grid.com/example-assets/row-data.json');    
  30.   }  
  32.   getSelectedRows() {  
  33.     const selectedNodes = this.agGrid.api.getSelectedNodes();  
  34.     const selectedData = selectedNodes.map(node => {  
  36.       return node.data;  
  37.     });  
  38.     const selectedDataStringPresentation = selectedData.map(node => node.make + ' ' + node.model).join(', ');  
  40.     alert(`Selected nodes: ${selectedDataStringPresentation}`);  
  41.   }  
Step 6 - Update Template
Replace the content of src/app/app.component.html with the following code, 
  1. <ag-grid-angular  
  2.     style="width: 620px; height: 500px;"  
  3.     class="ag-theme-alpine"  
  4.     [rowData]="rowData | async"  
  5.     [columnDefs]="columnDefs"  
  6. >  
  7. </ag-grid-angular> 
Step 7 - Run the app
We got the Grid,

B - Use the Angular Client to Consume Web API

We will try to use the Angular Client, built above, to consume our Web API built in the previous article. Before we make the test, we need to modify the Angular app to fit our dataset.
Basically, we only need to modify two major things: one is the entity class to fit our dataset, secondly, the remote endpoint of data, and we need to modify one minus: the data format.
In above Step 5, the Conponent file, we modify the hilighted blue parts, replace the dataset as below,
  1.   //   columnDefs = [  
  2.   //     { field: 'make', sortable: true, filter: true },  
  3.   //     { field: 'model', sortable: true, filter: true },  
  4.   //     { field: 'price', sortable: true, filter: true }  
  5.   // ];  
  7.     columnDefs = [  
  8.     { field: 'stor_Id', sortable: true, filter: true },  
  9.     { field: 'stor_Name', sortable: true, filter: true },  
  10.     { field: 'stor_Address', sortable: true, filter: true },  
  11.     { field: 'city', sortable: true, filter: true },  
  12.     { field: 'state', sortable: true, filter: true },  
  13.     { field: 'zip', sortable: true, filter: true },  
  14. ];  
Replace the http address as below,
  1. // this.rowData = this.http.get('https://www.ag-grid.com/example-assets/row-data.json');        
  2. this.rowData = this.http.get('https://localhost:44381/api/StoresWebAPI');     
And finally, in Step 6, the template file, we modify the highlighted blue format as below,
  1. <ag-grid-angular   
  2. <!-- style="width: 500px; height: 500px;" -->       
  3.     style="width: 1210px; height: 200px;"    
  4.     class="ag-theme-alpine"    
  5.     [rowData]="rowData | async"    
  6.     [columnDefs]="columnDefs"    
  7. >    
  8. </ag-grid-angular>    
Now, we can run the app, and assume we can get our Web API database back, but, we cannot: the data is loading, while never showing up,
This happened due to the different Origin issue: we view the web page at address: http://localhost:4200, while requesting backend data feed at port: 44381.
In this article, we will try to solve the problem by combining the two apps: client and server into one to make them having the same endpoint address, while in the next article, we try to enable CORS to access different origin remotely working.

C - Combine the Angular Client and Web API server to Make them having Same Origin

There are two approaches to merge the two apps together,
  •  Create an ASP.NET Core Web API app with Angular, and then insert the developed Angular app into the .NET project.
  •  Insert the Angular app into a well develped Web API server app
Approach 1 - Create an ASP.NET Core Web API app with Angular
For this, we still have two ways to do that:
  • Create an ASP.NET Core Web API app with Angular by Visual Studio
  • Create an ASP.NET Core Web API app with Angular by .NET Core CLI (Command Line Interface)
Way 1 - by Visual Studio
We use the current version of Visual Studio 2019 16.8 and .NET 5.0 SDK to build the app.
  1. Start Visual Studio and select Create a new project.
  2. In the Create a new project dialog, select ASP.NET Core Web Application > Next.
  3. In the Configure your new project dialog, enter Project name.
  4. Select Create.
  5. In the Create a new ASP.NET Core web application dialog, select,

    1. Select .NET Core and ASP.NET Core 5.0 in the dropdowns.
    2. Choose ASP.NET Core with Angular for the project template.
    3. Create
Run the app, and you will see,
Way 2 - by .NET Core CLI (Command Line Interface)
Run the app from Visual Studio: Open the generated .csproj file, and run the app as normal from there. The project will look like this,
From here, we can develop the project for both Web API and Angular from scrach. Suppose, we have a well developed Angular, then we just need to replace the code in ClientApp by the developed Angular code, then modify the folder name to ClientApp.
Approach 2 - Insert the Angular app into a well develped Web API server app
For this, we use the Web API .NET Core app developed in the previous article, use Angular app develped in this article:
  • Step 1: Add the Angular app folder, ag-Grid, into the Web API project root,
  • Step 2: Change the name as "ClientApp";
  • Step 3: Modify the http address in the Angular app the same as one for Web API project --- Same Origin:
  • Step 3,:Modify the Startup.cs file to run Angular, the Single Page Application;
  1. app.UseSpa(spa =>  
  2. {  
  3.     // To learn more about options for serving an Angular SPA from ASP.NET Core,  
  4.     // see https://go.microsoft.com/fwlink/?linkid=864501  
  6.     spa.Options.SourcePath = "ClientApp";  
  8.     if (env.IsDevelopment())  
  9.     {  
  10.         spa.UseAngularCliServer(npmScript: "start");  
  11.     }  
  12. }); 
 For UseSpa, we need to add the following:
NuGet - Solution X Browse Installed Updates Micro SO re-spa Consolidate x • Include prerelease Microsoft.AspNetCore.SpaServices.Extensions by Microsoft Helpers for building single-page applications on ASP.NET MVC Core.
 Now, run the app, we have it successfully running,


In this article, we made another Web API consumer, an Angular client, and showed the effect of the CORS issue. We use the same origin to solve the problem to make the combined app work in this article. In the next article, we will demostrate and analyze CORS for different situations.