Middleware is a crucial component in ASP.NET Core applications. It allows us to handle requests and responses in a flexible and organized manner. We’ll explore how to create conventional middleware in C# ASP.NET Core, which enables us to intercept HTTP requests and responses.
Middleware in ASP.NET Core sits between the client and the server, processing requests and responses. It’s like a pipeline through which every request passes, allowing it to perform various tasks such as logging, authentication, authorization, and more.
Let’s dive into creating a conventional middleware component step by step.
First, we need to create a class for our middleware. This class should have a method named InvokeAsync
, which accepts HttpContext
and RequestDelegate
parameters. Here’s a simple example:
using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Http;using System;using System.Threading.Tasks;namespace CustomMiddleware{public class MyCustomMiddleware : IMiddleware{public async Task InvokeAsync(HttpContext context, RequestDelegate next){await context.Response.WriteAsync("Hello middleware\n");//Perform middleware logicawait next(context); // call the next middleware}}public static class MyCustomMiddlewareExtensions{public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder app){return app.UseMiddleware<MyCustomMiddleware>();}}}
In the code, a class named MyCustomMiddleware
is defined which has an inheritance from IMiddleware
:
Line 8: The MyCustomMiddleware
class implements the IMiddleware
interface, which requires the implementation of the InvokeAsync
method (line 10). This method is called to handle each HTTP request.
Line 18: The MyCustomMiddlewareExtensions
class contains an extension method UseMyCustomMiddleware
that extends the IApplicationBuilder
interface (lines 20–23). This method adds the MyCustomMiddleware
to the middleware pipeline. It uses the UseMiddleware
method (line 22), passing MyCustomMiddleware
as the middleware type.
Inside the InvokeAsync
method of MyCustomMiddleware
, we can implement the logic that needs to be executed before or after the next middleware. For example, we print “Hello middleware” on the browser:
public async Task InvokeAsync(HttpContext context, RequestDelegate next){await context.Response.WriteAsync("Hello middleware\n");//Perform middleware logicawait next(context); // call the next middleware}
Next, we need to register our middleware in the Program.cs
file. Add the following line:
builder.Services.AddTransient<MyCustomMiddleware>(); // Register the middleware as service// Use the middleware using extension methodapp.UseMyCustomMiddleware();
Line 3 tells ASP.NET
Core to use our MyCustomMiddleware
for processing requests.
Let’s create a simple middleware that prints “Hello Middleware” as an example. Press the “Run” button to execute the code:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading.Tasks; namespace CustomMiddleware { public class MyCustomMiddleware : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { await context.Response.WriteAsync("Hello middleware\n"); //Perform middleware logic await next(context); // call the next middleware } } public static class MyCustomMiddlewareExtensions { public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder app) { return app.UseMiddleware<MyCustomMiddleware>(); } } }
We can see that our custom middleware gets executed before the main logic ("Hello world"
in this case) when the /
request is executed by the browser.
Middleware is a powerful feature in ASP.NET Core that allows us to intercept and process HTTP requests and responses. By creating conventional middleware, we can easily add custom logic to our application’s request pipeline. We’ve covered the basics of creating and using middleware in ASP.NET Core. Experiment with different middleware components to enhance the functionality and behavior of your applications.
Free Resources