Skip to main content

ASP.NET Core : Implement a custom middleware component

In ASP.NET Core, a middleware component is a class that implements the IMiddleware interface or is a class that has a method named Invoke or InvokeAsync. To create a custom middleware component, you can create a new class and implement the InvokeAsync method. Here is an example of a custom middleware component that logs the request and response information:

     public class RequestResponseLoggingMiddleware

    {

        private readonly RequestDelegate _next;

 

        public RequestResponseLoggingMiddleware(RequestDelegate next)

        {

            _next = next;

        }

 

        public async Task InvokeAsync(HttpContext context)

        {

            // Log the request information

            var request = context.Request;

            Console.WriteLine($"{request.Method} {request.Path}");

            foreach (var header in request.Headers)

            {

                Console.WriteLine($"{header.Key}: {header.Value}");

            }

 

            // Call the next middleware component

            await _next(context);

 

            // Log the response information

            var response = context.Response;

            Console.WriteLine($"{response.StatusCode}");

            foreach (var header in response.Headers)

            {

                Console.WriteLine($"{header.Key}: {header.Value}");

            }

        }

    }

  To use this middleware component in your application, you need to add it to the Startup.cs Configure method, this can be done by using the UseMiddleware<T> extension method:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {

        //...

        app.UseMiddleware<RequestResponseLoggingMiddleware>();

        //...

    }

 The order in which the middleware components are added to the IApplicationBuilder is important, the order that you add the middleware to the pipeline determines the order in which it is executed. Keep in mind that if you want your middleware component to perform some operation before or after other middleware components, you should add it accordingly in the pipeline.

Alternatively you can use the app.Use method as well, it's similar to UseMiddleware but it can be used for any type of middleware, not just classes that implement IMiddleware interface.

 

Comments

Popular posts from this blog

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods