Middleware in ASP.NET Core

C# Tutorials

Middleware is a piece of computer software that allows software ( such as an internet application) to communicate with databases, servers, and remote machines. Middleware handles the HTTP requests and HTTP responses between a client and a server, which helps developers build better and more efficient software architecture.

Read: Best Online Courses to Learn C#

In this programming tutorial, we discuss what middleware is, how it can be used, and look at some example of using ASP.NET Core middleware and C# to create web applications.

What is ASP.NET Middleware?

The ASP.NET Core middleware was introduced to lessen the dependency of .NET websites and applications on servers. Before the introduction of middleware, the request and response objects in .NET were tightly-coupled with web servers, which led to poor maintainability of code. Middleware, fortunately, mitigated this problem. In the next section, we will look at how middleware functions in a typical .NET website and leads to better code maintainability.

How does Middleware Work in .NET?

.NET Core middleware makes use of the request pipeline to handle HTTP requests. Developers can configure the request pipeline using different methods, such as run(), map(), and use.

The request pipeline decides whether an HTTP request should be passed to the next component in the pipeline for processing. Apart from that, the request pipeline also takes care of the required actions that need to be performed before – or after – the invocation of a component in the pipeline.

It should be noted that one application can make use of more than one middleware, depending upon the needs of the application. You can utilize the built-in middleware that comes with .NET Core or get them from the NuGet package manager. This is how the middleware functions.

Below are some of the different built-in middleware components available in .NET and their function:

  • Session: Used for user session management.
  • CORS: Used for Cross-origin Resource Sharing (CORS) constraint.
  • Routing: Used for defining and managing routes
  • Authentication: Used for authenticating users and roles

Read: Top Code Refactoring Tools for Developers

How to Set Up a Middleware Pipeline with ASP.NET

ASP.NET Middleware

Now that we have a better grasp of what middleware is, how it functions, its role in the request pipeline, and its components, let’s preview a practical example of how to set up a middleware pipeline for your ASP.NET website.

To achieve this, web developers need to make use of the configure() method, which is defined in the Startup class, whose function is to add the components below to the website lifecycle. It is important to note here that you should take care while defining the order of middleware, otherwise your application might not perform well or become unresponsive:

  • Model-View-Controller (MVC) with the area defined
  • Error handling
  • Session
  • Cookie Policy

We can better understand the importance of middleware through the following code example. Inside the configure() method of the Startup.cs class, we have the following C# code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/NotFound");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "blog",
        pattern: "blog/{*article}",
        defaults: new { controller = "Blog", action = "Article" });
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Books}/{action=Details}/{id?}");
});

Below is an outline of the workflow of the above code. In this example:

  • The first middleware we used in our example is for error handling. In the development environment we used UseDeveloperExceptionPage and in the production environment we used UseExceptionHandler.
  • Next in the pipeline, we have the UseHttpsRedirection middleware, which redirects the HTTP request to the secure HTTPS.
  • Then, we used UseStaticFiles middleware. Its function is to serve the static files to the browser by adding them to the request pipeline. Usually, static files are stored in the webroot folder and developers can access them through that path. However, it is up to the programmer; you can also store files in any other directory.
  • Next, we use the UseCookiePolicy that adds the CookiePolicyMiddleware handler to the specified request pipeline. It ensures the application should remain compliant with the General Data Protection Regulation (GDPR) standards, laws, and regulations.
  • After this, the next middleware used is UseSession. Its purpose is to provide support for user session management. If you forget to place this middleware, then you will not be able to access the session data.
  • Last up, we have UseMvc. This is the last middleware in our request pipeline. This should be placed at the end of the pipeline so that when it comes to action, all the authentication and session work gets completed.

Final Thoughts on Middleware and ASP.NET

Middleware is one of the beneficial features .NET provides for its developers. Middleware helps ASP.NET developers to develop their websites or web applications with more control over client-server communication. We can use various middleware depending on our project requirements or even create our own customized one.

Read more C# and ASP.NET programming and software development tutorials.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read