ASP.NET CORE Middleware

In this tutorials will discuss and understand what is the middleware and significant of the middleware’s.

What is Middleware ASP. NET Core? 

In ASP.NET Core, Middleware is a piece of code that are assembled into an application pipeline to handle an HTTP request or response. A given middleware component in ASP.NET Core has a very specific purpose. That means when we create as or add any middleware that is for Some specific purpose
 
For example we may have a middleware component that authenticates a user, another piece of middleware to handle errors, yet another middleware to serve static files such as JavaScript files, CSS files, Images etc.
 
In ASP.NET Core, a Middleware component has access to both the incoming request and the outgoing response. So a Middleware component may process an incoming request and pass that request to the next piece of middleware in the pipeline for further processing.
 
For example, if you have a logging middleware, it might simply log the time of the request is made and pass the request to the next piece of middleware for further processing.
 
A Middleware component may handle the request and decide not to call the next middleware in the pipeline. This is called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work.
 
For example, if the request is for a static file like an image or css file, the StaticFiles middleware can handle and serve that request and short-circuit the rest of the pipeline. This means in our
case, the StaticFiles middleware will not call the MVC middleware if the request is for a static file.
 
Middleware component are must be executed in order they added in pipeline. So need take care of
sequence execution of the middle otherwise it will not function as expected.
Request delegates are used to build the request pipeline. Request delegates are configured using Run, Map, and Use extension methods on the IApplicationBuilder type that is passed into the Configure method in the Startup class. An individual request delegate can be specified in-line as an anonymous method, or it can be defined in a reusable class. These reusable classes are middleware, or middleware components.
 

Middleware Pipeline

The ASP.NET core request pipeline consists a sequence of request delegates, called one after the next, as this diagram shows (the thread of execution follows the black arrows):

asp.net-core-middleware
 

Each delegate has the opportunity to perform operations before and after the next delegate. Any delegate can choose to stop passing the request on to the next delegate, and instead handle the request itself.

You can see an example of setting up the request pipeline in the default web site template.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseMiddleWareBefore();
    app.UseRouting();
    app.UseMiddleWareAfter();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Built in Middleware in ASP. NET Core

Exception Handling

      • UseDeveloperExceptionPage() & UseDatabaseErrorPage(): used in development to catch run-time exceptions
      • UseExceptionHandler(): used in production for run-time exceptions

Calling these methods first ensures that exceptions are caught in any of the middleware components that follow. For more information, check out the detailed post on Handling Errors in ASP .NET Core, earlier in this series.

HSTS & HTTPS Redirection:

      • UseHsts(): used in production to enable HSTS (HTTP Strict Transport Security Protocol) and enforce HTTPS.
      • UseHttpsRedirection(): forces HTTP calls to automatically redirect to equivalent HTTPS addresses.

Calling these methods next ensure that HTTPS can be enforced before resources are served from a web browser. For more information, check out the detailed post on Protocols in ASP .NET Core: HTTPS and HTTP/2.

Static Files:

      • UseStaticFiles(): used to enable static files, such as HTML, JavaScript, CSS and graphics files. Called early on to avoid the need for authentication, session or MVC middleware.

Calling this before authentication ensures that static files can be served quickly without unnecessarily triggering authentication middleware. For more information, check out the detailed post on JavaScript, CSS, HTML & Other Static Files in ASP .NET Core.

Cookie Policy:

      • UseCookiePolicy(): used to enforce cookie policy and display GDPR-friendly messaging

Calling this before the next set of middleware ensures that the calls that follow can make use of cookies if consented. For more information, check out the detailed post on Cookies and Consent in ASP .NET Core.

Authentication, Authorization & Sessions:

      • UseAuthentication(): used to enable authentication and then subsequently allow authorization.
      • UseSession(): manually added to the Startup file to enable the Session middleware.

Calling these after cookie authentication (but before the endpoint routing middleware) ensures that cookies can be issued as necessary and that the user can be authenticated before the endpoint routing kicks in.

Endpoint Routing:

      • UseEndpoints(): usage varies based on project templates used for MVC, Razor Pages and Blazor.
      • endpoints.MapControllerRoute(): set the default route and any custom routes when using MVC.
      • endpoints.MapRazorPages(): sets up default Razor Pages routing behavior
      • endpoints.BlazorHub(): sets up Blazor Hub

You can watch our video version of this tutorials with step by step explanation