How to build custom middleware in ASP.Net Core

Take advantage of ASP.Net Core middleware to customize your application’s handling of HTTP requests and responses

Become An Insider

Sign up now and get FREE access to hundreds of Insider articles, guides, reviews, interviews, blogs, and other premium content. Learn more.

ASP.Net Core is an open source, cross-platform, lean, and modular framework for building high-performance web applications. It is also extensible. When building an ASP.Net Core application, you can draw on various middleware components to customize the handling of requests and responses, and even inspect, route, or modify the request and response messages that flow through the pipeline. This article presents a discussion of ASP.Net Core middleware and how it can be used, with relevant code examples in C#.

Usually, you have a chain of middleware components in the application pipeline in ASP.Net Core. The ASP.Net Core request pipeline contains a series of request delegates that are invoked one after the other. Incoming requests flow through each of the middleware components in the pipeline, and each of these components can either process the request or pass the request to the next component in the pipeline.

Configuring the ASP.Net Core middleware pipeline

The middleware pipeline is configured using the Configure method in the Startup.cs file. This is exactly where you can chain together your ASP.Net Core pipeline. The Configure method is automatically called by the ASP.Net runtime. Here is a quick look at this method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IdentityDbContext dbContext)
    {
        app.UseDeveloperExceptionPage();           
        app.UseStaticFiles();          
        app.UseMvcWithDefaultRoute();
    }

To continue reading this article register now