Monday 5 October 2020

ASP.NET Core Custom Middleware

 Middleware is a component that's assembled into an app pipeline to handle requests and responses. ASP.NET Core provides a rich set of built-in middleware components, but in some scenarios you might want to write a custom middleware.

Middleware class
The custom middleware component is like any other .NET class with Invoke() method. However, in order to execute next middleware in a sequence, it should have RequestDelegate type parameter in the constructor.

The middleware class must include:

  1. A public constructor with a parameter of type RequestDelegate.
  2. A public method named Invoke or InvokeAsync. This method must:
      Return a Task.
      Accept a first parameter of type HttpContext.

Additional parameters for the constructor and Invoke/InvokeAsync are populated by dependency injection (DI).

Create Middleware Component

Visual Studio includes template for creating standard middleware class. For this, right click on the project or folder where you want to create middleware class and select Add -> New Item.
This will open Add New Item popup. Search for word "middleware" in the top right search box as shown below.

Select Middleware Class item and provide a name and click on Add button. This will add a new class for the middleware with extension method as shown below.

namespace MyDesk.Api.Middleware
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package
// into your project
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(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 CustomMiddlewareExtensions
    {
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}

As you can see above, the Invoke() method is not asynchronous. So, change it to asynchronous and write your custom logic before calling next();

namespace MyDesk.Api.Middleware
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package 
// into your project
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public CustomMiddleware(RequestDelegate nextILoggerFactory logFactory)
        {
            _next = next;
            _logger = logFactory.CreateLogger("CustomMiddleware");
        }

        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 CustomMiddlewareExtensions
    {
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}


Add Custom Middleware

Now, we need to add our custom middleware in the request pipeline by using Use extension method as shown below.

public void Configure(IApplicationBuilder appIHostingEnvironment env)
{
    app.UseCustomMiddleware();

    app.Run(async (context=>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

We can add middleware using app.UseMiddleware<MyMiddleware>() method of IApplicationBuilder also.

Reference: https://docs.microsoft.comhttps://www.tutorialsteacher.com/

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives