Add Custom Middleware In ASP.Net Core 6 App | RAJESH GAMI

 Custom Middleware in ASP.Net Core 6 App

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.

Logging Infrastructure .NET Core

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 > ();
    }
}
C#

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 > ();
    }
}
C#

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!");
    });
}
C#

You can also add middleware using the IApplicationBuilder 's app.UseMiddleware() method.

Therefore, you can add custom middleware to your ASP.NET Core application.

No comments:

Post a Comment

RAJESH GAMI - Blog

Digital Signature Pad in Angular | RAJESH GAMI

  What is Signature Pad? Signature Pad could be a JavaScript library for drawing fancy signatures. It supports HTML5 canvas and uses variabl...