Add Custom Middleware in ASPNET Core

Today in this article we will see how to add Custom Middleware in ASP.NET Core Application.

Today in this article, we will cover below aspects,

As we know Middleware is a component that is used in the application pipeline to handle requests and responses which can also help perform pre and post-operation within the API pipeline.

Getting Started

Let’s create an ASP.NET Core 3.1 or.NET 6 application.

Let’s create a very basic middleware component.

Create Custom Middleware component

Let’s create a very basic middleware component.

If you have Visual Studio IDE, then you can create middleware components using the file template available,

The above file template in Visual Studio gives you basic scaffolding and basic middleware class out of the box.

This file consists of the Middleware component with synchronous behavior.

Asynchronous Middleware Execution

To add support for asynchronous execution of middleware component, please add InvokeAsync() method as below,

public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong: {ex.Message}");
            }
        }
    }

Synchronous Middleware Execution

If middleware needs to support synchronous execution of middleware components then please add the Invoke() method as below,

public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            try
            {
                _next(httpContext);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong: {ex.Message}");
            }
        }
    }

Middleware extension method

Use the below extension method to invoke the middleware through IApplicationBuilder.

public static class GlobalCutomMiddleware
    {
        public static void UseGloabalCustomMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<CustomMiddleware>();
        }
    }


Finally, use the below code to enable middleware using UseGloabalCustomMiddleware() method in the API pipeline,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseGloabalCustomMiddleware();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }


Reference:

That’s All! Happy Coding!

Please sound off your comments below.

Summary

Middleware components play an important role in the API pipeline and today we looked at How to add Custom middleware in the API pipeline container in the ASP.NET Core application.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *