ASP.NET Core API - Day One - Getting Started And Request Pipeline

Introduction

This tutorial will focus on ASP.NET Core features, request pipeline, how to create an ASP.NET Core API and how to use an Entity Framework Core. We willl try to create an API with an ASP.NET Core and tries to establish the communication with the database to perform simple CRUD operations via an Entity Framework Core. The series will contain continuation articles to cover the topic in detail and we will end up having a functional Application.

Prerequisites

Since we start from the beginning, it is expected that the reader of this article/series is new to ASP.NET Core and does not really have the insights of what is it all about. Having said that, we will stick to our aim of starting and learning an ASP.NET Core from the scratch. We will use Visual Studio 2017 Enterprise edition for the entire series, but one can also use Visual Studio 2015 or the Community editions of Visual Studio. The best part about ASP.NET Core Applications is that they can also be developed with Visual Studio codes, which executes at OS X and Linux. To check the requests and response from the API, we will use a tool named Postman. It’s free and easy to use. Alternatively, one can use the tool of a choice for e.g. Fiddler.

Roadmap

We will follow a roadmap to learn and cover all the aspects of an ASP.NET Core in detail. Following is the roadmap or the list of articles, which we will cover in the entire series.

ASP.Net Core

  1. Create API with ASP.Net Core (Day 1): Getting Started and ASP.NET Core Request Pipeline
  2. Create API with ASP.Net Core (Day 2): Create an API and return resources in ASP.NET Core
  3. Create API with ASP.Net Core (Day 3): Working with HTTP Status Codes and returning sub resources in ASP.NET Core API
  4. Create API with ASP.Net Core (Day 4): Working with Serializer Settings and Content Negotiation in ASP.NET Core API
  5. Create API with ASP.Net Core (Day 5): Understanding Resources in ASP.NET CORE API
  6. Create API with ASP.Net Core (Day 6): Inversion of Control and Dependency Injection in ASP.NET CORE API
  7. Create API with ASP.Net Core (Day 7): Getting Started with Entity Framework Core
  8. Create API with ASP.Net Core (Day 8): Entity Framework Core in ASP.NET CORE API
ASP.NET Core

There is always a buzz with Microsoft to provide something like an open source, cross platform and more or less related to the mobility. Thus, in general ASP.NET Core is the answer to all that buzz. It is an open source framework with the cross platform capabilities, which could be leveraged to build Cloud based Applications, which are connected through the internet. One can develop any kind of Application like normal Web Applications, API or mobile based Applications. Its beauty of being an open source and cross platform, which enables a developer to also contribute to the code or customize the code available, as per the need or requirement and cross the platform barrier and develop the Applications for Windows, Mac as well as for Linux. Another interesting offering by an ASP.NET Core is that it can be run on full .NET framework or on only .NET Core. We know what .NET framework is, but what .NET Core is? In simple words, .NET Core is the modular version of .NET Framework or one can say that it is the subset of full .NET Framework.

“ASP.NET Core is a lean and composable framework for building web and cloud applications. ASP.NET Core is fully open source and available on GitHub. ASP.NET Core is available on Windows, Mac, and Linux.” from https://www.asp.net/core

We call it modular because it is released via NuGet in the assembly packages rather than one large assembly, which contains most of the core functionality. When we read about .NET Core, we also come across something called .NET Standard. .NET Standard is a standard , which specifies a common layering that a platform should support and .NET Core is the implementation did by Microsoft for the .NET Standard.

Installing ASP.NET Core

For Visual Studio 2017, .NET Core Tools are included in the installer. One can find the installation guide at https://www.microsoft.com/net/core#windowsvs2017.

ASP.Net Core

If someone uses Visual Studio 2015, installing .NET Core tools is not that tough, as one can download .NET Core SDK and tooling for Visual Studio. The current .NET Core version is 1.1 but that too depends upon when you are reading this article, so the version may be different, which depends on when one is reading this post. One can find all the installation related SDK, tooling and platform specific installers at

https://www.microsoft.com/net/download/core.

ASP.Net Core

As soon as .NET Core is installed, one can start creating .NET Core projects. To verify that .NET Core is installed, open your Visual Studio, navigate to File-> New Project and one can see .NET Core project templates installed there.

ASP.Net Core

.NET Core Project and its Structure

Moving on to some hands on exercise, we will create a sample ASP.NET Core project, try to understand the project structure and other details. We will create a fresh ASP.NET Core Web Application from the scratch.

Open your Visual Studio, navigate to File -> New project; where you can see the available .NET CORE templates and filter for ASP.NET Core Web Applications, as shown below.

After filtering, we can see two options available in the templates, one saying to create ASP.NET Core Web Application using >NET Core and other says, using .NET Framework. We earlier discussed the difference between .NET Core Application and .NET Framework Application and also know that ASP.NET Core Web Application can be developed, using any of the two options depending upon our choice and need. We will choose .NET Core option as we just need to focus on this area and do not really require other capabilities of complete .NET Framework. We will try to create an API, which returns information of the employees. Therefore., we’ll name our API as EmployeeInfo.API and name the solution as EmployeeInfo, as shown below.

ASP.Net Core

Click OK and we get the list of the templates, which we need to choose to create our Application. When we choose the template, the other dependent and additional files will be added to the project via NuGet.

ASP.Net Core

Note that we can also choose the current ASP.NET Core version i.e. 1.1 or the earlier stable version as well, which was 1.0. Out of the three available templates, since we are in the process of creating an API, we can choose Web API template but that may again end up downloading unnecessary Nuget packages and default controller structure that we really do not require. The purpose of this article is to make .NET Core Application from the scratch to have better understanding and get better concept. To understand each and every thing, let’s start from the empty template, so that we have full control to add what exactly do we want. Thus, choose “Empty” and press OK button. NuGet Restore will download the required packages to support an empty template, which we choose and will we see that the created empty project contains some structure and the basic code, as shown beelow.
below
ASP.Net Core

We got a solution named EmployeeInfo and a project named EmployeeInfo.API i.e. our ASP.NET Core project. There are two classes added i.e. Program.cs and Startup.cs. We can closely look into these classes and understand them.

Program.cs

ASP.Net Core

Program.cs acts as a starting point of the Application like every other console Application in .NET. It contains the Main method as the starting point. Thus, we see that ASP.NET Core in general is a console Application that talks to ASP.NET specific components and the libraries. Application configuration and execution is the responsibility of Main method here. We know that to run a Web Application, it needs to be hosted and we also need to do that. If we lool closely  into the Main method, we see that WebHostBuilder is initialized and since we host the Web Application, there is a need of Web Server now. The beauty of an ASP.NET Core is that it is decoupled from the environment, which the Web Server provides for hosting the Web Application. It is accompanied with two HTTP Servers, where the first is WebListener i.e. a Windows based Web Server and another is Kestrel i.e. a Web Server for cross platform Application hosting. Thus, the statement UseKestrel signifies Kestrel as the default. Since we are currently inside Visual Studio, so it will, by default use IIS Express as a default host. The statement UseIISIntegration specifies that IIS Express works as a reverse proxy Server for Kestrel. If there is a need to deploy an ASP.NET Core Application on the Windows Server, one should run IIS as a reverse proxy Server for Kestrel and if the Application has to be deployed on Linux, one should use a comparable reverse proxy Server like Apache to proxy requests to Kestrel.

One can independently self-host the Application, using Kestrel but using IIS as a reverse proxy gets a lot of advantages. For example, IIS can filter the requests, manage the SSL layer and certificates and make sure the Application restarts, if it crashes and so on.

UseContentRoot statement signifies the root directory of the content used by the Web host. As default, the content root remains same as the Application base part for the executable, which is hosting the Application. One can specify an alternate location, as per the need via passing location in the UseContentRoot statement but for now; we can stick to the default current directory. The line UseStartup signifies the startup type, which has to be used by the web host. Startup is the second class, which we got in the empty Web Application at the time of creation. Build statement means that it builds an iWeb host instance to host our Web app. At the end, host.run will eventually run the Application and blocks the calling thread till the host shuts down completely.

Startup.cs

ASP.Net Core

Theoretically, the Startup class is the entry point for an Application. As shown in the image, it contains two methods. ConfigureServices method is used to add and configure Services to the container, which is used for Dependency Injection. A Service in context of an ASP.NET Core is a component, which is created for common consumption in an Application. For e.g. there are framework related Services, as Identity MVC Entity framework core Services, but there are Application Services, which are Application specific. For example, we can add an Application specific Service to send a mail or logging, which could be made available for Dependency Injection via registering it in ConfigureServices method.

The Configure method takes IApplicationBuilder, IHostingEnvironment and ILoggerfactory instances provided by the container. Note that ConfigureServices is an optional method but the Applications at some point of time will require at least some Services, which are not already automatically registered. Configure method is called after the ConfigureServices method because it uses Services, which are registered and configured in that method. It specifies the behavior of an ASP.NET Core Application on the individual HTTP requests. This is the place, where our Application in the upcoming articles will handle HTTP requests with the help of MVC. Currently, as per default implementation, each and every HTTP request will print Hello World on the screen. When we run the application, first as expected, ConfigureServices will be called, then Configure method will be called that prints Hello World on the screen. You can check the control flow by putting break points and running the Application.

ASP.Net Core

ASP.NET Core Middleware and Request Pipeline 
 
The components, which are involved in handling the requests and generating the results in response are responsible to make up the request pipeline. We can always add a middle ware component to the pipeline in between to handle the requests and responses. In earlier or old versions of ASP.NET, there was a concept of modules and handlers, which use to take care of the requests and responses. In ASP.NET Core, this is done by middleware. For e.g. a middle ware could be added in the request pipeline to handle authentication and authorization.

MVC has its own middleware, which can be added to the request pipeline. Whenever a request comes, it comes inside request pipeline, and request pipeline contains the list of requests, which are delegated one after another from one middleware component to another.


ASP.Net Core

Each middleware has an option to perform operations before receiving and after delegating the request and eventually generate the response needed. Thus, each middleware component decides whether to delegate the request onto the next component or not. For example,  authentication middleware component finds the request is not authorized and it will not pass the request to the next component in the pipeline and return the response result from its own component.

Configure Request Pipeline

Let’s try to configure the request pipeline of an ASP.NET Core. We’ll try to configure it in a way that a developer friendly exception page is shown as soon as an exception is thrown by the Application. We already have an empty Application which we created and if we check the Configure method of Startup class, we see app.UseDeveloperExceptionPage() method called within Configure method and it is called by first checking that if the Application is in the developer environment or not, so half of our work is already done by this empty template. 

  1. if (env.IsDevelopment())  
  2.     {  
  3.         app.UseDeveloperExceptionPage();  
  4.     }   

This method basically configures our request pipeline in a way that it adds the middleware of the developers exception page, so when  an exception will be thrown in the developers mode, this middleware is responsible to handle this.

Press F12 on this method to see the assemble details and we find that it is the part of assemble Microsoft.AspNetCore.Diagnostic.

ASP.Net Core

Likewise, one can find various middleware in various separate assemblies, which shows the modularity of an ASP.NET Core.

Let’s check what happens in case any exception has occurred. We will modify the Configure method and throw an exception instead of showing “Hello World”. 

  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  2.     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  3.     {  
  4.       loggerFactory.AddConsole();  
  5.   
  6.       if (env.IsDevelopment())  
  7.       {  
  8.         app.UseDeveloperExceptionPage();  
  9.       }  
  10.   
  11.       app.Run(async (context) =>  
  12.       {  
  13.         throw new Exception("Test Dev Exception Page");  
  14.       });  
  15.   
  16.       //app.Run(async (context) =>  
  17.       //{  
  18.       //  await context.Response.WriteAsync("Hello World!");  
  19.       //});  
  20.     }   

Since we have already configured the request pipeline to show the details of the exception on the developer’s exception page, we should ideally see one. Thus, run the Application and an exception is thrown, since we are throwing exception knowingly, continue with the exception by pressing F5 and we see a developer’s exception page, as shown below.

ASP.Net Core

Since this is a developer’s exception page, it will only be shown during development and not when the Application is in production.

If we navigate to the Debug tab inside project properties, as shown below.

ASP.Net Core

We find an environment variable named ASPNETCORE_ENVIRONMENT set to “Development” ASP.NET Core refers a unique environment variable and hosting environment to maintain the environment an Application is currently running in. It could be set to one of the three conventional values. That are Development, Staging and Production, but the good thing is that we can add our own also.

These values can be accessed programmatically and we make use of IHostingEnvironment Service.

ASP.Net Core

From env variable, one can access all the information related to hosting environment, as shown below.

ASP.Net Core

Since we needed to have developer’s exception page is shown when an app is in development mode, we used the UsedeveloperExceptionPage, else we would have catched the exception or logged it, and to do so, ASP.NET Core also provides a middle ware i.e. an exception handler middleware. One can pass the parameters to UseExceptionHandler() method for e.g. to show a user friendly error page.

ASP.Net Core

For now, let’s stick to our default implementation.

Let’s try to change the development environment to production.

ASP.Net Core

Now, run the Application. We get a friendly error page, which can be made more meaningful, when a parameter is passed to UseExceptionHandler() method.

ASP.Net Core
Now, to check the exception here, open the developers tool i.e. press F12 on the page. In the console, we see the exception has been thrown twice.

ASP.Net Core

One for the favorite icon and another one that was expected from the application. That means that exception handler middleware also logs the exception, so which part is responsible for logging the exception. Back to Configure method, we see the ILoggerFactory injected by default, and that is responsible for logging the exception. We’ll cover this topic in detail in later parts of the series.

Conclusion

In this article, we learned about how to get started with ASP.NET Core. We learnt that ASP.NET Core is open source and made to build cross platform Cloud based internet Applications. We figured out how it is different from a complete .NET Framework. We also explored how to install and create a basic Service Application with an ASP.NET Core and explored what are request pipelines and middleware. We also learnt about how to configure the request pipeline through middleware and got some interesting insights of an ASP.NET Core.

Source Code on Github

Source Code

References

  • https://www.asp.net/core
  • https://www.pluralsight.com/courses/asp-dotnet-core-api-building-first

Up Next
    Ebook Download
    View all
    Learn
    View all