CHAPTER 4
In this chapter, you are going to learn about the main innovations of the latest version of ASP.NET that have dramatically changed from the previous version. In particular, you are going to see why ASP.NET Core is defined as a lean framework and how to manage static files, different hosting environments, exceptions, dependency injection, and all the other significant features of the latest release.
You can better understand how to use .NET Core by first creating a new empty application with Visual Studio 2017. If you prefer the superlight VS Code instead of Visual Studio, you must use the command line to create an empty template.
When creating a new ASP.NET Core template from Visual Studio, you have different options. To better understand the flow and all the components you need for a web application, the empty template is the best choice.

Figure 4-1: New Web Application Using Visual Studio 2017
Looking at the Solution Explorer, notice that the folder structure and files are very different from the previous version of ASP.NET. First of all there, is a wwwroot folder that contains all the static files.
In a different section, we will explain how to use the wwwroot folder and the reason why you need it.
All files in the root of the project are either new additions or they changed their role:
As mentioned before, this class is the entry point of the .NET Core application, and its role is to create the host for the web application. Since we can host our web application on different web servers with .NET Core, this is the right place to configure everything.
Code Listing 4-1
using System; |
As you can see, this class is simple, as the only two important methods are UseKestrel and UseIISIntegration, respectively used to host the application on Kestrel or IIS.
The ASP.NET Core pipeline starts here, and, as you can see from the following code, almost nothing comes with the template.
Code Listing 4-2
using System; |
What’s important here are the methods ConfigureServices, where dependency injection is configured (we’ll talk about this later in the chapter), and Configure, where all needed middleware components are registered and configured.
Tip: We already wrote a book about OWIN, so if you don't know what a middleware component is or how to use it, we suggest you read the free e-book OWIN Succinctly, available from Syncfusion.
The app.Run method is a perfect example of an inline middleware component. In this case, it is useless because the web application will always return the text string "Hello World!", but more complex logic (i.e. authentication, monitoring, exception handling, and so on) can be added.
One of the biggest new features of ASP.NET Core is the inclusion of a way to handle dependencies directly inside the base library. This has three major benefits.
Before looking at how to use dependency injection inside ASP.NET Core applications, let's see what it is and why it is important to use.
In order to be easy to maintain, systems are usually made of many classes, each of them with very specific responsibilities. For example, if you want to build a system that sends emails, you might have the main entry point of the system and one class that is responsible for formatting text and then one that is responsible for actually sending the email.
The problem with this approach is that, if references to these additional classes are kept directly inside the entry point, it becomes impossible to change the implementation of the helper class without touching the main class.
This is where dependency injection, usually referred to as DI, comes into play. Instead of directly instantiating the lower-level classes, the high-level modules receive the instances from the outside, typically as parameters of their constructors.
Described more formally by Robert C. Martin, systems built this way adhere to one of the five SOLID principles, the dependency inversion principle:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
—Robert C. "Uncle Bob" Martin
While manually creating and injecting objects can work in small systems, they can become unmanageable when systems grow in size and hundreds or thousands of classes are needed. To solve this problem, another class is required: a factory that takes over the creation of all objects in the system, injecting the right dependencies. This class is called container.
The container, called an Inversion of Control (IoC) container, keeps a list of all the interfaces needed and the concrete class that implements them. When asked for an instance of any class, it looks at the dependencies it needs and passes them based on the list it keeps. This way very complex graphs of objects can be easily created with a few lines of code.
In addition to managing dependencies, these IoC containers also manage the lifetime of the objects they create. They know whether they can reuse an instance or need to create a new one.
This a very short introduction of a very important and complicated topic related to the quality of software. Countless articles and books have been written about dependency injection and SOLID principles in general. A good starting point are the articles by Robert C. "Uncle Bob" Martin or by Martin Fowler.
Now that you understand the importance of using DI in applications, you might wonder how to configure it. It is actually easy. It all happens in the ConfigureServices method.
Code Listing 4-3
public void ConfigureServices(IServiceCollection services) |
The parameter the method accepts is of the type IServiceCollection. This is the list used by the container to keep track of all the dependencies needed by the application, so it is to this collection that you add your classes.
There are two type of dependencies that can be added to the services list.
First, there are the ones needed by the frameworks to work, and they are usually configured using extension methods like AddServiceName. For example, if you want to use ASP.NET Core MVC, you need to write services.AddMvc() so that all the controllers and filters are automatically added to the list. Also, if you want to use Entity Framework, you need to add DBContext with services.AddDbContext<ExampleDbContext>(...).
Then there are the dependencies specific to your application; they must be added individually by specifying the concrete class and the interface it implements. Since you are adding them yourself, you can also specify the lifetime of the service. Three kinds of lifecycles are available in the ASP.NET Core IoC container, and each of them has to be added using a different method.
The first is Transient. This lifecycle is used for light-weight services that do not hold any state and are fast to instantiate. They are added using the method services.AddTransient<IClock,Clock>() and a new instance of the class is created every time it is needed.
The second lifecycle is Scoped. This is typically used for services that contain a state that is valid only for the current request, like repositories and data access classes. Services registered as scoped will be created at the beginning of the request and the same instance will be reused every time the class is needed within the same request. They are added using the method services.AddScoped<IRepository, Repository>().
The last lifecycle is called Singleton, and as the name implies, services registered this way will act like singletons. They are created the first time they are needed and reused throughout the rest of the application. Such services typically hold application state like an in-memory cache or similar concern. They are added via the method services.AddSingleton<IApplicationCache, ApplicationCache>().
Let's now see an example of how DI-IoC is used in an ASP.NET MVC application. ASP.NET MVC is covered in detail in a later chapter, so don't worry if something looks unfamiliar; just focus on how dependencies are configured and reused.
To use dependency injection, you need four classes:
First, you have to define the interface of the service, the only thing the consumer depends on.
Code Listing 4-4
public interface IClock |
Once the interface is defined, you need to implement the concrete class that does the actual work.
Code Listing 4-5
public class Clock: IClock |
For the sake of this example, you are going to slightly modify the HomeController that comes with the default project template. The most important change is the addition of a constructor and a private variable to hold the reference of the external dependency.
Code Listing 4-6
private readonly IClock _clock; |
Obviously, you also have to use the dependency somehow. For this example, just write the current time in the About page by modifying the About action method.
Code Listing 4-7
public IActionResult About() |
The following listing is the complete file.
Code Listing 4-8
public class HomeController : Controller |
Now that all elements are in place, you just need to configure the framework so that it injects the right class (Clock) in all objects that declare a dependency of type IClock as a parameter of the constructor. You’ve already seen how this has to be done via the ConfigureServices method.
Code Listing 4-9
public void ConfigureServices(IServiceCollection services) |
The first line configures the application to use ASP.NET Core MVC, and the second one adds our simple clock service. We've shown how to use dependency injection in an ASP.NET application using a very simple external service that just gives the time, but the main elements needed are all there:
Every application we deploy needs to handle at least two or more environments.
For example, in a small application, we have the development environment (also known as dev), the production environment, and in some cases the staging environment.
More complex projects need to manage several environments, like quality assurance (QA), user acceptance test (UAT), preproduction, and so on. In this book, we show only what comes out of the box with ASP.NET Core; however, you can easily understand how to add a new environment.
One of my favorite features of ASP.NET Core, which is included with the framework, is what is called Hosting Environment Management. It allows you to work with multiple environments with no friction. But before diving deeper into this feature, you have to understand what the developer needs are.
A good developer should never work on a production database, production storage, a production machine, and so on. Usually, in a .NET application, a developer manages this problem using the applicationSettings section in the web.config file combined with Config Transformation Syntaxt (more info at MSDN) and Preprocessor Directives.
This approach is tricky and requires you to build the application differently for each environment because the config transformation and the preprocessor directive are applied at compile time. Last but not least, this approach makes your code hard to read and maintain.
As you may have noticed in the previous chapters, the web.config file is used only to configure the AspNetCoreModule in case our application must be hosted on Internet Information Services (IIS); otherwise, it is useless.
For this reason, don’t use the Config Transformation approach—use something cooler.
ASP.NET Core offers an interface named IHostingEnvironment that has been available since the first run of our application. This means we can easily use it in our Startup.cs file if we need it.
To know that, the implementation of IHostingEnvironment reads a specific environment variable called ASPNETCORE_ENVIRONMENT and checks its value. If it is Development, it means you are running the application in Dev mode. If it is Staging, you are running the application in a staging mode. And so it goes for all the environments you need to manage.
Because this approach is based on an environment variable, the switch between the configuration files happens at runtime and not at compile time like the old ASP.NET.
Visual Studio has a run button, which is pretty awesome for developers because it runs the application attaching the debugger. But what environment will be used by Visual Studio when you push the run button?
By default, Visual Studio uses development mode, but if you want to change it or configure a new environment, you can do it easily by looking at the file launchSettings.json, available in the Properties folder of your application.
If you open it, you should have something like this:
Code Listing 4-10
{ |
The iisSettings section contains all the settings related to IIS Express, while the profile section contains the Kestrel configurations. If you are familiar with the JSON format, you can edit all these values in Visual Studio by following these steps:

Figure 4-2: Change IIS Express Settings 1

Figure 4-3: Change IIS Express Settings 2
From here, you can also change the settings in the case of Kestrel by using the dropdown menu at the top. If you prefer to work directly with JSON and want to change the environment, change the value for ASPNETCORE_ENVIRONMENT, and then save the file or add a new item in profiles section with our settings.
Sometimes a web application needs something more than switching the connection string from a developer database to a production database. For example, you may need see the stack trace of an error in case you are running the app on a local machine, or you may need to show a error page to the end user in the production version.
There are several ways to do that. The most common is undoubtedly to inject the IHostingEnvironment interface into your constructor and use it to change the behavior of your app. The following simple code is a possible startup class.
Code Listing 4-11
using System; |
In this example the DeveloperExceptionPage Middleware is used only in case your application is running in a dev mode, which is exactly what we want.
What you did in this class can be repeated in any part of your code as a controller, a service, or however it needs to be different among the environments.
The Startup class is absolutely the most important class in your application because it defines the pipeline of your web application, and it registers all the needed middleware components.
Because of this, it might be very complex with lots of lines of code. If you add checking for the environment, everything could be more complicated and difficult to read and maintain.
For this reason, ASP.NET Core allows you to use different startup classes: one for each environment you want to manage or one for different "Configure" methods.
Let's look at the Program.cs file:
Code Listing 4-12
public class Program |
The method .UseStartup<Startup>() is very clever. It can switch between different classes automatically if you are following the right convention (method name + environment name).
For example, if you duplicate the Startup class and rename it StartupDevelopment, the extension method will automatically use the new one in the development environment.
You can use the same convention for the Startup class methods. So, duplicate the method Configure of the Startup.cs file, call it ConfigureDevelopment, and it will be called instead of the original one only in the development environment.
We already mentioned environments like user acceptance test (UAT) or quality assurance (QA), but the IHostingEnvironments interface doesn't offer a method IsUAT() or IsQualityAssurance, so how can you create one?
If you think on it, the answer is pretty easy. It is enough to assign a new value to the ASPNETCORE_ENVIRONMENT variable using a set command in a command shell (i.e. QualityAssurance) and create an extension method like this:
Code Listing 4-13
using Microsoft.AspNetCore.Hosting; |
Now, remaining on the previous example, we can use the extension method like this:
Code Listing 4-14
using System; |
In subsequent chapters, you will see how to use IHostingEnvironments in views or configuration files.
One of the main features of ASP.NET Core is that it can be as lean as you like.
This means you are responsible for what you’re going to put into the application, but it also means you can make the application very simple and fast.
In fact, if you start your project from an empty ASP.NET Core web application template, the application will not be able to serve static files. If you want to do it, you have to add and configure a specific package.
A common question is “Why doesn't it support static files by default if all web sites need static files?"
The truth is that not all websites need to serve static files, especially on high-traffic applications. In this case, the static files should be hosted by a content delivery network (CDN).
Moreover, your web application could be an API application that usually serves data using JSON or XML format instead of images, stylesheets, and JavaScript.
As you’ll see by reading this book, most of the configurations are managed by middleware components available on NuGet. That’s also true in this case; you have to install a specific package and configure its middleware.
The package to install is Microsoft.AspNetCore.StaticFiles. You can get it using the Package Manager.

Figure 4-4: Install Static Files Package Using NuGet
Code Listing 4-15
using Microsoft.AspNetCore.Builder; |
You are almost ready. The last, but still important, thing to know is that the wwwroot folder present in the root of your project will contain all the static files so, if you want to serve a file called image1.jpg for the request http://localhost:5000/image1.jpg, you have to put it into the root of the wwwroot folder, not in the root of the project folder like you were doing with the previous version of ASP.NET.
Another scenario where the static file middleware component combined with ASP.NET Core application could be very useful is for a web app that is a single page application (SPA).
The best way to describe the meaning of SPA is the Wikipedia's definition:
A single-page application (SPA) is a web application or web site that fits on a single web page with the goal of providing a user experience similar to that of a desktop application.
Basically, most of the business logic is present on the client. The server doesn't need to render different views; it just exposes the data to the client. This is available thanks to JavaScript (combined with modern frameworks like Angular, React, Aurelia) and a set of APIs (in our case, developed with ASP.NET MVC Core).
If there is no server-side rendering, the web server must return a static file when the root domain is called by the browser (http://www.mysite.com). To do that, you have to configure the default documents into the Configure method of your Startup class.
If you’re okay with the default documents being preconfigured (default.htm, default.html, index.htm, and index.html) it is enough to add UseFileServer like this:
Code Listing 4-16
using Microsoft.AspNetCore.Builder; |
Otherwise, if you need to use a specific file with a different name, you can override the default configuration and specify your favorite files as default documents:
Code Listing 4-17
using Microsoft.AspNetCore.Builder; |
You can write the best code in the world, but you must accept the fact that errors exist and are part of life. From a certain point of view, you could say that a good application is one that can identify an error in the shortest possible time and return the best possible feedback to the user.
To achieve this goal, you need to deal with different actors, like logging frameworks, exception handling, and custom error pages.
We have dedicated a section later in this chapter regarding logging frameworks. That’s why we are not showing how to configure the logging output here. For now, it is enough to know that out-of-the-box ASP.NET Core logs all the exceptions, so you don't need to create an exception middleware component of a specific code to log unhandled exceptions.
Of course, if you don't like what comes with the framework, you still have the opportunity to write our own exception handler. The first thing to do is throw an exception into your empty application.
Code Listing 4-18
using System; |
If you run the application and add the variable called throw to the query string like this— http://localhost:5000/?throw (in this case, the application is running using Kestrel with the default configuration)—you should receive an output as follows (although the output page could be different for each browser):

Figure 4-5: Default 500 Error
As you can see, there isn’t useful information, and the feedback isn’t user friendly. This is because ASP.NET, for security reasons, doesn't show the stack trace of the exception by default; the end user should never see this error from the server. This rule is almost always valid except when the user is a developer creating the application. In that case, it is important to show the error.
As demonstrated in the section on environment, it's easy to add this only for a development environment.
Fortunately, ASP.NET Core has a better error page than the old YPOD (yellow page of death) generated by the previous version of the ASP.NET. To use the new, fancy error page, you must be sure to install the Microsoft.AspNetCore.Diagnostics package from NuGet.
Now, at the beginning of you Configure method, it is enough to add this line of code:
Code Listing 4-19
// This method is called by the runtime. Use this method to configure the HTTP request pipeline. |
Restart the web server again from Visual Studio, refresh the page, and the output should contain more useful information.

Figure 4-6: Developer exception page
On this page, there are four important tabs:
For reasons already explained, you can't show the error information on a production environment, so you have to choose between two possible ways:
Let's see the first option:
Code Listing 4-20
app.UseStatusCodePagesWithRedirects("~/errors/{0}.html"); |
In this case, you should create one page for each status code you want to manage and put it on a folder called errors in the wwwroot folder (combined with the UseStaticFiles middleware component, of course).
If you can't use static files, it is enough to remove .html from the string passing through the method and add a specific route on MVC. If you prefer the second option, using another middleware component will suffice:
Code Listing 4-21
UseStatusCodePagesWithReExecute("~/errors/{0}"); |
Finally, your error management could be this:
Code Listing 4-22
if (_env.IsDevelopment()) |
How ASP.NET Core handles configuration files significantly changed with the new version. Previously, you used the AppSettings section of the web.config file, but now web.config is not needed by ASP.NET. It is there only if you have to host an application on Internet Information Services (IIS); otherwise, you can strip it out.
If the AppSettings section isn’t needed anymore, how do you store information?
The answer is simple. You use external files (you can have more than one). Fortunately, there is a set of classes that help to manage that. And although it may seem more uncomfortable, it isn’t.
First, choose the file format you prefer. The most common format is JSON, but if you are more familiar with XML, use it.
Let's suppose you have an appsettings.json file like this:
Code Listing 4-23
{ |
The more comfortable way to have all this information in a C# application is by using a class with a set of properties. In a perfect world, it would be a class with the same structure of JSON, like this:
Code Listing 4-24
namespace Syncfusion.Asp.Net.Core.Succinctly.Environments |
At this point, it injects the C# classes with the values from the JSON file. Because the configuration file is usually needed at the beginning of the application lifecycle, you have to add the lines of coded to the Startup class—or more accurately, into the constructor. Before doing this, however, you need to add some packages:
There’s no need to say more about the purpose of the packages; their names speak for themselves. So, let's see how the code looks:
Code Listing 4-25
private readonly IHostingEnvironment hostingEnvironment; |
We already explained the importance of having different environments and how to manage them via C#. The same applies to the configuration.
More than ever, you now need different configuration files—one for each environment. Thanks to ASP.NET Core, this is easy to manage.
To take advantage of what the framework offers, you have to follow a few rules: the first one is related to configuring file names.
For different files, having one for each environment allows you to add the environment name into the file name. For example appsettings.json for the development environment must be called appsettings.Development.json and appsettings.Production.json would be used for a production environment.
The second rule is related to the differences among the files. You don't need to have the complete JSON copied in each configuration file because ASP.NET Core will merge the files, overriding only what is specified in the environment configuration file.
To understand what this means, imagine you have the same database instance but a different database name. You can log in to the database server using the same credentials, but the same server hosts both from production to development; it just switches the database.
To cover this scenario and keep using the appsettings.json file you used before, look at the appsettings.Development.json file.
Code Listing 4-26
{ |
And look at appsettings.Production.json.
Code Listing 4-27
{ |
This is awesome because you can keep the configuration files very lean, but now you need to educate ASP.NET Core to handle multiple configuration files. To do that, change the code you wrote previously to this:
Code Listing 4-28
private readonly IHostingEnvironment hostingEnvironment; |
Now, for a development environment, you will get my-development-db-name as the database name; otherwise, it will be my-production-db-name. Remember to keep the same JSON structure in your environment configuration files.
This last part is related to the use of the configuration values across the application, such as the controller, services, and whatever else needs to read the configuration values.
Register the instance of configuration class you created earlier to the ASP.NET Core dependency injection container. As usual, go into the Startup.cs class and register the instance.
Code Listing 4-29
public void ConfigureServices(IServiceCollection services) |
For configuration scenarios, the Singleton lifecycle is the best option. To get the values into the services, inject the instance on the constructor.
Code Listing 4-30
namespace Syncfusion.Asp.Net.Core.Succinctly.Environments |
Logging is very important in a web application, and it is very difficult to implement. This is why so many logging frameworks are available. Search the term "logging" on nuget.org, and you’ll see there are more than 1,900 packages.

Figure 4-7: NuGet Logging Packages
Of course, not all are logging frameworks, but almost all are related to logging. Logging is very individualized. It is related to the particular environment or application you are working on.
Modern applications are composed of several packages. The combination of both (several logging frameworks and several packages) makes the logging ecosystem very complicated. What happens if each package uses its own logging framework or one that is different from the one used in your application?
It would be a complicated mess to configure each one for each environment. You’d probably spend a lot of time configuring logging instead of writing good code.
To solve this problem, before ASP.NET Core, there was a library called Common.Logging .NET (the official repository is on GitHub) that provided a simple logging abstraction to switch between different logging implementations, like Log4net, NLog, Serilog, and so on.
It would be pretty cool if all packages use this, because you could configure the logging once in a single place. Unfortunately, this doesn't allow you to log the code that comes from the .NET Framework because it doesn't have dependencies as opposed to external libraries.
With ASP.NET Core, this problem is completely solved. You don't have to use the Common.Logging .NET library because the framework offers something similar out of the box, and it is integrated with all the packages.
First, you have to choose the output of the log you want—for example, a console application, a trace source, an event log, and so on. For Kestrel, it could be very helpful to use the console output. Add the Microsoft.Extensions.Logging.Console using Visual Studio package manager.

Figure 4-8: Managing NuGet Packages Using Visual Studio

Figure 4-9: Installing Console Logging
The package Microsoft.Extensions.Logging.Console could already be installed if you used one of the templates available with Visual Studio 2015.
Now, in the Startup class, configure the log output. As explained in previous sections, the Configure method is the best place to do this. LoggingFactory is the class responsible for generating the log instance.
Code Listing 4-31
using Microsoft.AspNetCore.Builder; |
Visual Studio and VS Code offer an incredible feature called IntelliSense, so when typing loggerFactory., it suggests all available options. If we did everything correctly, we should get the following.

Figure 4-10: Adding Console Provider
The best part of this logging system is that it is natively used by the ASP.NET Core Framework. When running the application, you should see the output depicted in Figure 4-12.

Figure 4-11: Running a Web Application Using Kestrel

Figure 4-12: Web Application Console Output
Each request is logged twice: the first when the server receives the request and the second when the server completes the request. In Figure 4-12, there are four logs in two groups: the first when the browser requests the page and the second when it requests the favicon.
Without tuning the configuration, the log implementations write all information into the output. To restrict large amounts of data in the log output, you can configure it to log only information starting from a specific level. ASP.NET Core logging has six levels:
In a production environment, you probably want to log starting from the Warning or Error level. To do this, specify the right minimum log level in the AddConsole method.
Notice that each logger implementation has a different way to specify the minimum level of logging, so this implementation could not work with TraceSource or EventLog.
Code Listing 4-32
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) |
You’ve seen how to configure the log and its output with the .NET Core framework, but you didn't see how to use it in classes. Thanks to dependency injection, it is very easy—just inject the logger instance into the constructor and use it.
The class to inject is ILogger<T>, where T is the class that needs to be logged.
Code Listing 4-33
using Microsoft.Extensions.Logging; |
In this book, we are not going to explain how to create your own custom logger, but there are several repositories where you can see how to do that. Here Is a short list:
In this chapter, you learned how to use middleware components to implement features needed by web applications, such as static files, exception handling, dependency injection, hosting, and environment.
Other cool features are available—like data protection and caching. To find out more, go to www.asp.net.