Angular and MVC Core Architecture together in a nutshell: a real world example part 3
Welcome to the third part of this serie where we will be focus to the server side development of the sample project, in this post, we will talk about asp.net MVC Core framework architecture especially why is asp.net middleware and how dependency injection help to simplify web development, we also try to explain how Asp.net MVC Core toolchain work and how you can integrate it to Angular toolchain as descibe in part 1 and part 2, we will also get in touch with Entity framework(EF) core by building a REST api to comunicate with a sql database using EF Object Relation Mapping(ORM) system. Record that our sample project it’s base on an Azure data Center Monitoring web tool, where you want to give to non Azure administrator, a tool to monitore the azure virtual machine cluster metric like CPU and Memory usage, in this case, we are supposed that, this data will be read daily from the Azure platform by using Azure SDK o REST API (like application insight REST O SDK) and save those metric data inside remote on premise DB, so that the angular frontend we build in the first and second part will consume it, the “non administrators” of this Azure monitoring data center web site we are building, will be not only able to view metrics data, but can edit some content in the DB (in another post we would see how you can use asp.net core identity or Azure active directory to build the administrtion part of this sample project). In the last part, MongoDB will be put in the fray to hold a part of metrics data so that we can see how to split our application in multiple part and deploy it as microservices in Azure cluster PAAS solutions. You can download the full project as we build in part 2 here from my github account.
Ok we are ready to begin our Asp.net core MVC server side project, we will continue to use command line to create the project struture, so go ahead and open a command line and navigate to “ AzureDataCenterMonitoring” folder and run the following command (I’ll be running it inside visual studio code new terminale to make it simple):
mkdir ServerApp
cd ServerApp
dotnet new globaljson --sdk-version 3.0.100These commands create a “AzureDataCenterMonitoring/ServerApp” folder, which will contain the ASP.NET Core MVC project. The dotnet new globaljson command creates a file named global.json that specifies the
version of the .NET Core runtime that will be used, which will help ensure the examples work as expected. By default, the latest version of the .NET Core SDK is used to create new projects, which may mean you get
inconsistent results if you have a version installed that is later than the one specified in the first part of this series. Now run the command bellow inside the AzureDataCenterMonitoring/ServerApp folder to create the ASP.NET
Core MVC project.
dotnet new mvc --language C# --auth NoneThe dotnet new command adds all the files required for a basic ASP.NET Core MVC project to the AzureDataCenterMonitoring/ServerApp folder, alongside the Angular project created in the previous post.

If you are using Visual Studio, select the File ➤ Open ➤ Project/Solution menu, navigate to the AzureDataCenterMonitoring/ServerApp folder, and select the ServerApp.csproj file. Visual Studio will open the project
in .NET mode and will hide some of the files that were previously shown in the Solution Explorer window. Right-click the Solution item at the top of the Solution Explorer window and select Add ➤ Existing Website from the popup menu. Navigate to the AzureDataCenterMonitoring folder, select the ClientApp folder, and click the Open button. Visual Studio will add the ClientApp folder to the Solution Explorer so that you can see the contents of the Angular project. Right-click the ClientApp item, select Property Pages from the popup menu, and navigate to the Build section. Make sure that the “Build Web site as part of solution” option is unchecked, This configuration change prevents Visual Studio from trying to compile the code in the Angular
project. Select File ➤ Save All; Visual Studio will prompt you to save the solution file, which can be used to open the Angular and ASP.NET Core MVC projects when you want to pick up a development session. Save the file
in the AzureDataCenterMonitoring folder using the name AzureDataCenterMonitoring.sln. When you need to open the project again, open the AzureDataCenterMonitoring.sln file; both parts of the project will be opened and displayed in the Solution Explorer window.
Now row the command bellow inside ServerApp folder to generate the development HTTPS certificates (Select the Yes option for each prompt that Windows presents)
dotnet dev-certs https –clean
dotnet dev-certs https --trustThe ASP.NET Core MVC part of the project can be compiled and executed from the command line or using the code editor. To build and run the project from the command line, run the command shown bellow inside the ServerApp folder
dotnet watch runat you can gess from the result of the above command, your server side asp.net core site it’s available on port 5000 as in this image

How ASP.NET Core MVC Toolchain work?
The development tools for ASP.NET Core MVC are entirely different from those used by Angular. The C# compiler processes the statements in the C# code files and generates output that can be executed by the .NET Core runtime. When the application is started, HTTP requests are received by Internet Information Services (IIS) or the stand-alone ASP.NET Core Kestrel server and handled by the ASP.NET Core request pipeline (we will be more describe in the last section of this post), which is the backbone of ASP.NET Core applications and allows MVC applications, RESTful web services, and other frameworks to coexist in the same application.
The template used to create the project includes the MVC framework. Requests are handled by the Home controller defined in the ServerApp/Controllers folder, which selects the Index.cshtml view file in
the ServerApp/Views/Home folder. The MVC framework uses the Razor view engine to process the view, producing the HTML that is sent back to the browser and displayed to the user. The image bellow describe what going on while running an asp.net core MVC application:

The request pipeline is the heart of ASP.NET Core and is built around a series of middleware components that are able to inspect requests and either modify them or produce results. The most interesting middleware
for this book integrates the MVC framework, but almost every ASP.NET Core feature relies on middleware to some extent, including serving static content and redirecting HTTP requests to the HTTPS URL.
The dotnet watch run command used to start the application puts .NET Core into watch mode, such that it detects changes to the files in the ServerApp folder and automatically recompiles the code and restarts the application.
What is a middleware and how is work?
The word middleware is used in a variety of contexts in software development and IT, but it’s not a particularly descriptive word — what is middleware?
In ASP.NET Core, middleware is C# classes that can handle an HTTP request or response. Middleware can
- Handle an incoming HTTP request by generating an HTTP response.
- Process an incoming HTTP request, modify it, and pass it on to another piece of middleware.
- Process an outgoing HTTP response, modify it, and pass it on to either another piece of middleware, or the ASP.NET Core web server.
You can use middleware in a multitude of ways in your own applications. For example, a piece of logging middleware might note when a request arrived and then pass it on to another piece of middleware. Meanwhile, an image-resizing middleware component might spot an incoming request for an image with a specified size, generate the requested image, and send it back to the user without passing it on. The most important piece of middleware in most ASP.NET Core applications is the MvcMiddleware class. This class normally generates all your HTML pages and API responses . Like the image-resizing middleware, it typically receives a request, generates a response, and then sends it back to the user, look at the figure bellow:

This arrangement, where a piece of middleware can call another
piece of middleware, which in turn can call another, and so on, is referred to
as a pipeline. You can think of each piece of middleware as a section of pipe
when you connect all the sections, a request flows through one piece and into
the next.
One of the most common use cases for middleware is for the cross-cutting concerns of your application. These aspects of your application need to occur with every request, regardless of the specific path in the request or the resource requested. These include things like:
Logging each request
Adding standard security headers to the response
Associating a request with the relevant user
Setting the language for the current request
In each of these examples, the middleware would receive a request, modify it, and then pass the request on to the next piece of middleware in the pipeline. Subsequent middleware could use the details added by the earlier middleware to handle the request in some way. For example, in the image bellow , the authentication middleware associates the request with a user. The authorization middleware uses this detail to verify whether the
user has permission to make that specific request to the application or not.
If the user has permission, the authorization middleware will pass the request on to the MVC middleware to allow it to generate a response. If the user doesn’t have permission, the authorization middleware can short-circuit the pipeline, generating a response directly. It returns the response to the previous middleware before the MVC middleware has even seen the request.
A key point to glean from this is that the pipeline is bidirectional. The request passes through the pipeline in one direction until a piece of middleware generates a response, at which point the response passes back through the pipeline, passing through each piece of middleware for a second time, until it gets back to the first piece of middleware. Finally, this first/last piece of middleware will pass the response back to the ASP.NET Core web server.

Connecting the Angular and ASP.NET Core Applications
The Angular and ASP.NET Core MVC applications share the same parent folder but are not connected in any way. It is possible to develop applications this way, but it is awkward. A more useful approach is to connect the two toolchains so that HTTP requests are received by ASP.NET Core and passed on to either the MVC framework or the Angular development tools based the request URL.
There are two ways to connect the toolchains, and each is useful during a different phase of the project lifecycle. Both approaches rely on an additional .NET package. Open a new PowerShell command
prompt, navigate to the ServerApp folder, and run the command shown in Listing bellow (in visual studio code just open a new terminal window):
dotnet add package Microsoft.AspNetCore.SpaServices.Extensions --version 3.0.0The Microsoft.AspNetCore.SpaServices.Extensions package is provided by Microsoft to allow single-page application (SPA) frameworks, such as Angular, to be used with ASP.NET Core.
The most commonly used connection technique is to configure the ASP.NET Core runtime so that it starts the Angular development server when the first HTTP request is received. This has the advantage of requiring
only a single command to start both toolchains, which can be done via the command line or using the built-in features provided by Visual Studio and Visual Studio Code. The drawback is that restarting ASP.NET
Core will also restart the Angular development server, which means the initial compilation process will be repeated for each restart, which can take 10 to 20 seconds every time.
Modify your Startup class to configure ASP.NET Core so that it is
responsible for managing the Angular development server and for selecting the connection approach based on a configuration setting. So open ths Startup.cs file and add an using statement like this in the top of the page
using Microsoft.AspNetCore.SpaServices.AngularCli;Then you can now add the spa middleway at the end of the Configure(IApplicationBuilder app, IWebHostEnvironment env) method like in the following snippet:
app.UseSpa(spa => {
spa.Options.SourcePath = "../ClientApp";
spa.UseAngularCliServer("start");
});your full startup class will look like this:
You can view the code in my github repository here.
The new code invokes the UseSpa method to add a middleware component to the ASP.NET Core request pipeline. The argument to the UseSpa method is a function that receives a configuration object ; the argument is used in this example to specify the location of the Angular project and to specify the NPM
command used to start the Angular development tools. The UseSpa method is used in development only and will be removed before the application is deployed . ASP.NET Core works its way through the middleware components in the sequence in which they are defined, which means that the Angular development server will receive only those requests that have not
been handled by another middleware component, such as the one that applies the MVC framework. Use Control+C to stop both the Angular development server and the ASP.NET Core runtime and then
use the command prompt to run the command shown bellow in ServerApp folder
dotnet run watchOpen a web browser and navigate to https://localhost:5001; you will see the content generated by the MVC framework, as we have been see before.
Next, navigate to https://localhost:5001/app; you will see the output from the Angular application, as shown in the second screenshot in the image bellow.

The first URL is handled by the MVC framework because the default URL is translated into a request for the Index action on the Home controller by this statement in the Startup class

The app segment of the second URL doesn’t correspond to the name of an MVC controller, so the MVC framework can’t handle the request, which is then forwarded to the Angular development server. There is no special significance of the /app URL, and any URL with a segment that doesn’t match a controller name would have the same effect.

The alternative connection technique is to start the Angular development tools separately from the ASP. NET Core runtime. Requests are still forwarded to the Angular server, but the ASP.NET Core runtime isn’t responsible for starting the Angular tools. In this approach, restarts are faster, which can create a smoother flow during iterative development. Each part of the project responds independently so that a change to a C# class, for example, doesn’t affect the Angular development server. The drawback of this approach is that you need to run two commands and monitor two streams of output to see messages and errors. If we want to go in this way, Add the statements shown in the snippet bellow to the Startup class to configure ASP.NET Core MVC to forward requests to the Angular development server, along with statements that select the connection technique based on configuration settings (be sure to replace the last middleware we have added to the configure method with this new one).
The Configuration object is used to read the value of ConnectionStrategy in the DevTools section. If the setting is managed, then the technique from the previous section is used. If the setting is proxy, then the UseSpa method is used to specify the URL of the Angular server as an argument to the
UseProxyToSpaDevelopmentServer method.
To select the managed option, add the configuration settings shown in Listing bellow to the appsettings.Development.json file. (If you are using Visual Studio, this file is accessed by expanding the appsettings.json file item in the Solution Explorer window.)

you can now start the angular side project independently from the server side part by running “npm start or ng serve — port 5300 -o” in the ClientApp folder and run “dotnet watch run” to ServerApp folder.
Once both servers are running, open a new browser and navigate to https://localhost:5001 and then https://localhost:5001/app. You will see the same results as in the previous section because requests are
being forwarded in the same way. The difference is that the Angular server has been started independently.
When a request cannot be handled by ASP.NET Core, it is forwarded to the Angular development server. The Angular development server falls back to returning the index.html file in the ClientApp/src folder if the request URL doesn’t specify one of the bundle files or a file from the assets folder, which is where static content is usually stored in a stand-alone Angular project.
To increase the integration between Angular and the MVC framework, we are going to update the default Razor layout and the Views/Home/Index view so that only the bundle files are delivered by the Angular server. First, replace the contents of the _Layout.cshtml file in the ServerApp/Views/Shared folder with the elements in the snippet bellow.
This layout includes the Bootstrap CSS stylesheet,(Bootstrap was added to the project by the dotnet new command used to create the project).
There are sections for the main body and the script elements that will contain the Angular application bundles. To provide the content and the script elements required by the application, replace the contents
the Index.cshtml file in the ServerApp/Views/Home folder with the elements shown in Listing bellow.
Save the changes, allow the ASP.NET Core runtime to restart, and use the browser to navigate to https://localhost:5001. You will see that the Razor view has included the elements and bundle files that are required to display the Angular application.
I the next post, we build the model of our server side aps.net core MVC application and put EF(Entity framework core) in context, we also see how to integrate mongodb, and at the end of this series, we will be able to deploy the whole solution to microsoft azure as a cluster of contanirized application. Stay tuned, and see you to the next post. Share share and share.
NB: in you would like to get deep inside Angular development just read : Angular in action by “Jeremy Wilken” or become a ninja with angular by “Cédric Exbrayat” or progressive web app with angular (PWA) by “Hajian, Majid”. For asp.net MVC core developement, I recommend “Pro asp.net MVC core 2” by “Freeman, Adam” or asp.net core in action by “Andrew Lock”.
