📜 ⬆️ ⬇️

Quick Start Guide: Linking ASP.NET Core Web API + Angular 5

The story of how to make friends two separate projects ASP.NET Core Web API and Angular 5, and make them work as one.

Introduction


This article is designed for beginners who make the first steps in exploring Angular in conjunction with the .NET Core.

If you use Visual Studio for development, you probably have already met with ready-made project templates with Angular connected. These templates allow in a couple of clicks to create an application that already has a configured router and several ready-made components. You do not need to spend time on the minimum setting of the working application: you already have a working WebPack, a separate module for common components, a configured router, a connected Bootstrap. You might think, “Super! Cool! Half the deed is done! ” But in fact, everything is a little more complicated ...

The difficulty and pitfalls are that this approach has several significant drawbacks in the standard templates:
  1. Rigid connection of the web interface with the server side
  2. Strongly complicated minimally working version of the application
  3. Lack of ability to use Angular CLI
  4. Extra pre-installed packages
  5. Breaking Some Principles from the Angular Style Guide

Different best-practices advise us to split the application into two separate projects , which in our case is the .NET Core Web API and Angular projects. The main advantages of this approach will be the following:
  1. Two independent projects, which will allow us to further implement an alternative interface, without touching the project with the server part
  2. Narrowed global search scope , which allows you to search more efficiently and easily
  3. Abstraction from the working environment in which the server part is developed, Visual Studio for example - we can use VS Code, Sublime Text, Atom or another editor that is convenient for you

In this scenario, there are two final scenarios for production:
  1. You host the web interface at one address, and the server at another.
  2. Or you collect projects in one magic way and host only him

My task was just the second scenario , so it was more preferable for economic reasons. And so, when I tried to figure out how to make friends with the .NET Core Web API project with the Angular project, so that during development we had two separate projects, and in production - only one , and specifically. NET Core web site, I could not find a full-fledged guide "from scratch to a working application." It was necessary to collect piecemeal solutions from English-speaking forums and blogs. If you suddenly had the same task, then it will be enough to read my article.
')

Go!


So what will we use? We will need the following things:

If you already have Visual Studio 2017 installed and during installation you chose .NET Core Development , then you already have the .NET Core SDK and do not need to install it. However, Node.js will have to be installed separately even if Node.js Development was selected. Npm will install with Node.js. Angular CLI is installed globally from the command line via npm (the instruction is from the link above).

Now we need to check whether everything is installed and ready to go. To do this, open a command prompt (terminal) and execute the following commands in a row:

dotnet --version # .NET Core node --version # Node.js npm --version # npm ng --version # Angular CLI 

Result of the command line (versions may differ, no problem)


Create a .NET Core Web API project


In this article, I will perform all actions through the command line and VS Code, as it supports .NET Core. However, if you prefer Visual Studio 2017 for working with .NET projects, then you can safely create and edit a project through it.

Step one


We create the root folder of the project Project , open it in VS Code, start the terminal by pressing Ctrl + ~ (tilde, letter ). So far nothing complicated :)

VS Code window and running terminal


Step two


Now we need to create a project. To do this, run the command:

 dotnet new webapi -n Project.WebApi 

Open Code VS Code window and launched terminal


Step Three


We check everything works. Through the terminal go to the folder with the newly created project, then execute the command:

 dotnet run 

Open Code VS Code window and launched terminal


Step Four


If at the last step everything went well and Now listening on: localhost : 5000 was output to the console, it means that the server has been successfully started. Let's go to the address localhost : 5000 / api / values (test controller, which is created automatically). You should see JSON with test data.

Result in the browser


Step five


We return to VS Code and in the terminal press Ctrl + C to stop the server.

Open Code VS Code window and launched terminal


Create a project Angular


Now create an Angular project. For this we will use the commands Angular CLI, VS Code and the built-in terminal.

Step one


In the terminal, go to the root folder of our Project Project and create a new project called Project.Angular (you have to wait a bit):

 cd ..\ ng new Project.Angular 

Open Code VS Code window and launched terminal


Step two


Go to the terminal in the folder just created the project and run it:

 cd ./Project.Angular ng serve --open 

Open Code VS Code window and launched terminal


Step Three


If at the last step everything went well and the NG Live Development Server was listening on localhost: 4200 , the server was successfully started. Go to localhost : 4200 . You should see the Angular test page.

Result in the browser


Step Four


We return to VS Code and in the terminal press Ctrl + C , enter Y to stop the server.

Open Code VS Code window and launched terminal


We configure the Angular project


Now we need to configure two things: proxy.config.json to redirect requests to the server to the correct port, and the most important thing is to set up the build in the wwwroot folder.

Step one


Create a file called proxy.config.json in the root of the Project.Angular project and add the following content to it:

 { "/api/*": { "target": "http://localhost:5000/", "secure": false, "logLevel": "debug" } } 

proxy.config.json
 { "/api/*": { "target": "http://localhost:5000/", "secure": false, "logLevel": "debug" } } 


This setting indicates that all requests starting with / api / ... will fall on localhost : 5000 /. That is, the resulting query will be localhost : 5000 / api / ...

Step two


We indicate Angular that in development mode we need to use this proxy.config. To do this, open the package.json file (which is also there, in the root), find the command scripts -> start and replace the value with:

 { ... scripts: { ... "start": "ng serve --proxy-config proxy.config.json", } } 

package.json
 { { "name": "project.angular", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.config.json", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^5.2.0", "@angular/common": "^5.2.0", "@angular/compiler": "^5.2.0", "@angular/core": "^5.2.0", "@angular/forms": "^5.2.0", "@angular/http": "^5.2.0", "@angular/platform-browser": "^5.2.0", "@angular/platform-browser-dynamic": "^5.2.0", "@angular/router": "^5.2.0", "core-js": "^2.4.1", "rxjs": "^5.5.6", "zone.js": "^0.8.19" }, "devDependencies": { "@angular/cli": "1.6.7", "@angular/compiler-cli": "^5.2.0", "@angular/language-service": "^5.2.0", "@types/jasmine": "~2.8.3", "@types/jasminewd2": "~2.0.2", "@types/node": "~6.0.60", "codelyzer": "^4.0.1", "jasmine-core": "~2.8.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~2.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "^1.2.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.1.2", "ts-node": "~4.1.0", "tslint": "~5.9.1", "typescript": "~2.5.3" } } } 


In the future, we will use the npm start command together with ng serve to start the Angular project. The npm start command is an abbreviation for the command that is listed in your package.json.

Step Three


The final step will be to simply set up the build (by command) of the project in the wwwroot .NET Core Web API folder of the project. In the open package.json file, we find the scripts -> build command and replace the value with the following:

 { ... scripts: { ... "build": "ng build --prod --output-path ../Project.WebApi/wwwroot", } } 

package.json
 { { "name": "project.angular", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.config.json", "build": "ng build --prod --output-path ../Project.WebApi/wwwroot", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^5.2.0", "@angular/common": "^5.2.0", "@angular/compiler": "^5.2.0", "@angular/core": "^5.2.0", "@angular/forms": "^5.2.0", "@angular/http": "^5.2.0", "@angular/platform-browser": "^5.2.0", "@angular/platform-browser-dynamic": "^5.2.0", "@angular/router": "^5.2.0", "core-js": "^2.4.1", "rxjs": "^5.5.6", "zone.js": "^0.8.19" }, "devDependencies": { "@angular/cli": "1.6.7", "@angular/compiler-cli": "^5.2.0", "@angular/language-service": "^5.2.0", "@types/jasmine": "~2.8.3", "@types/jasminewd2": "~2.0.2", "@types/node": "~6.0.60", "codelyzer": "^4.0.1", "jasmine-core": "~2.8.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~2.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "^1.2.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.1.2", "ts-node": "~4.1.0", "tslint": "~5.9.1", "typescript": "~2.5.3" } } } 


To perform this action, run the npm run build command in the terminal. The result will be the compiled project files in the wwwroot folder.

Configuring the .NET Core Web API project


It remains to teach the server to work with static files and allow requests from another port.

Step one


Open Startup.cs and add lines to the Configure method that allow the server to process static files:

 app.UseDefaultFiles(); app.UseStaticFiles(); 

Configure method in Startup.cs
  public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); } 


Step two


In Startup.cs , in the Configure method, add a line allowing the server to accept requests from port 4200:

 app.UseCors(builder => builder.WithOrigins("http://localhost:4200")); 

Configure method in Startup.cs
 public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseCors(builder => builder.WithOrigins("http://localhost:4200")); app.UseMvc(); } 


Step Three


In the ConfigureServices method we add support for CORS:

 services.AddCors(); 

ConfigureServices method in Startup.cs
 public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddMvc(); } 


Ultimately, the Startup.cs file must have the content that is presented below:

 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Project.WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddCors(); // <--   } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); // <--  app.UseStaticFiles(); // <--   app.UseCors(builder => builder.WithOrigins("http://localhost:4200")); // <--   :) app.UseMvc(); } } } 

Done! Now you can feel free to contact your API controllers from the Angular project. Also, by calling the npm run build command for the Angular project, you will have the version of the Web API of the application ready for deployment.

Conclusion


It was a quick guide to what you need to do in order to have two separate projects, and make them work as one.

Configuring CORS and building automation do not even claim to be a production version. However, you now know where to look and dig. I hope my article will be useful for someone. Personally, I just did not have enough of it when I tried to establish communication between these two technologies.

In this article, I did not highlight a few points related to routing in the Web API project, more flexible configuration of CORS, automatic assembly, etc. There are plans to write a more detailed article on how to assemble a production version of this version of the application already. If you have any questions, please write in the comments or on any of the contacts listed in the profile, I will try to help you.

Source: https://habr.com/ru/post/349522/


All Articles