Take advantage of ASP.NET Core middleware to customize your application’s handling of HTTP requests and responses. Credit: Thinkstock 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(); } The above code snippet illustrates how you can add MVC to the ASP.NET Core request execution pipeline. In the next section, we will build a custom middleware component for ASP.NET Core. Create an ASP.NET Core project in Visual Studio Assuming that you have .NET Core installed in your system (preferably .NET Core 2), you can follow these steps to create a new ASP.NET Core project in Visual Studio 2017 or Visual Studio 2015. Open Visual Studio Click File -> New -> Project In the New Project dialog window, select the ASP.NET Core Web Application project template Specify the name and location for your project and click OK to save In the next screen, select Web API from the list of templates, unselect authentication and Docker support (we don’t need either of these for now), and save the project And that’s all you need to do to create an ASP.NET Core web application that leverages Web API. We will now build a custom middleware component that checks if the authentication key passed in the request is valid. If the authentication key is not valid, the request will be rejected with an appropriate message. Create a custom ASP.NET Core middleware component You have an extension method in IApplicationBuilder that you can take advantage of to build your own middleware in ASP.NET Core. Note that it is always a good practice to write your middleware component in a separate class or a separate project so that you can update the middleware if need be, without having to change your service layer. There are various ways to build a custom middleware component—I will demonstrate the simplest way. Right-click on the project in the Solution Explorer window and create a new .cs file named MyCustomMiddleware. At first glance, this class will look like this. public class MyCustomMiddleware { //This is our custom middleware } Note that your custom middleware should have a constructor with a parameter of type RequestDelegate. A RequestDelegate is a just another delegate that accepts an HttpContext and returns a Task. Here is how the modified version of our custom middleware should look. public class MyCustomMiddleware { private readonly RequestDelegate _next; public MyCustomMiddleware(RequestDelegate next) { _next = next; } } Invoke your custom ASP.NET Core middleware Your middleware should also have a method that will be called when the middleware is executed. This is the Invoke method as shown in the code listing below. Note that this method has been named Invoke in this example only by convention. It is here that you can write your code to inspect or modify the requests and responses. public class MyCustomMiddleware { private readonly RequestDelegate _next; public MyCustomMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext) { if (!httpContext.Request.Headers.Keys. Contains(“Authentication-Key”)) { httpContext.Response.StatusCode = 400; await httpContext.Response.WriteAsync (“Authentication key is missing...”); return; } else { //Write code here to validate the authentication key. } await _next.Invoke(httpContext); } } Refer to the code listing given above. If the request header does not contain a valid authentication key, then an appropriate message will be returned as a response when you run your Web API. (Note that ”Authentication-Key” is a string that would be compared against a list of valid keys.) Create an extension method for ASP.NET Core middleware Let’s now create an extension method for our custom middleware. The purpose of the extension method is to make it easier to register the middleware to the pipeline. The ASP.NET team recommends exposing an IApplicationBuilder extension method that can be called from the Configure method. Here’s how you can build an extension method that takes advantage of IApplicationBuilder. public static class MyCustomMiddlewareExtensions { public static IApplicationBuilder UseMyCustomMiddleware (this IApplicationBuilder builder) { return builder.UseMiddleware<MyCustomMiddleware>(); } } Lastly, you should configure your custom middleware in the Configure method as shown below. Then you can use your extension method — e.g. UseMyCustomMiddleware()— as illustrated in the code snippet given below. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMyCustomMiddleware(); } Middleware in ASP.NET Core allows us to create very flexible web applications. Our authentication key example is just one of many ways we might take advantage of middleware. You can learn more about ASP.NET Core middleware from this article in the ASP.NET Core documentation. Related content opinion The dirty little secret of open source contributions It isn’t the person making the contributions—it’s how easy the contributions make it to use the software. By Matt Asay Nov 18, 2024 4 mins Technology Industry Open Source news ‘Package confusion’ attack against NPM used to trick developers into downloading malware Attackers gunning for supply chains again, deploying innovative blockchain technique to hide command & control. By John E. Dunn Nov 06, 2024 4 mins Vulnerabilities Open Source Security news Meta offers Llama AI to US government for national security US government agencies and private sector partners can now use the Llama model, but many other restrictions on its use remain. By Prasanth Aby Thomas Nov 05, 2024 1 min Generative AI Open Source Artificial Intelligence news OSI unveils Open Source AI Definition 1.0 The Open Source AI Definition will provide a reference for determining whether an AI system is truly open source AI, OSI said. By Lynn Greiner Oct 28, 2024 7 mins Generative AI Open Source Artificial Intelligence Resources Videos