What is Middleware?
Middleware is software embedded in the app pipeline that processes requests and responses. ASP.NET Core provides a rich set of built-in middleware components, but in some scenarios, you may need to write custom middleware.
Let's see with a practical example
Learn how to create your own custom middleware and add it to your ASP.NET Core application's request pipeline.
A custom middleware component is like any other .NET class with an Invoke() method. However, the constructor needs her RequestDelegate type parameter to execute the following middlewares in order:
Visual Studio includes templates for creating standard middleware classes. To do this, right-click the project or folder where you want to create the middleware class and select Add -> New Item. This will open the Add New Item popup. In the top right search box, search for the word "middleware" as shown below.
Select the class and give it a name and then click on Add.
This will look as shown below. (Middleware class added with extension method)
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) {
_next = next;
}
public Task Invoke(HttpContext httpContext) {
return _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions {
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder) {
return builder.UseMiddleware < MyMiddleware > ();
}
}
As mentioned above, the Invoke() method is not asynchronous. So change it to asynchronous and write your custom logic before calling next();
//------------------------- Async Middleware :Rajesh Gami-----------------------
public class MyMiddleware {
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public MyMiddleware(RequestDelegate next, ILoggerFactory logFactory) {
_next = next;
_logger = logFactory.CreateLogger("MyMiddleware");
}
public async Task Invoke(HttpContext httpContext) {
_logger.LogInformation("MyMiddleware executing..");
await _next(httpContext); // calling next middleware
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions {
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder) {
return builder.UseMiddleware < MyMiddleware > ();
}
}
Add Custom Middleware
Next, we need to add our custom middleware to the request pipeline using an extension method as shown below.
Add Middleware into Request Pipeline:
//************ Startup.cs *************
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseMyMiddleware();
app.Run(async (context) => {
await context.Response.WriteAsync("Hello Rajesh Gami!");
});
}
You can also add middleware using the IApplicationBuilder 's app.UseMiddleware() method.
Therefore, you can add custom middleware to your ASP.NET Core application.