DEV Community

yogini16
yogini16

Posted on

Intro Middlewares in .Net Core

Few basic details about .net middleware.

In .NET Core, middlewares are components that are added to the application pipeline to handle requests and responses. They can perform various tasks such as authentication, logging, caching, compression, routing, and more. Middlewares are executed in the order they are added to the pipeline, and each middleware can choose to pass the request to the next middleware or handle the response itself.

Let's see example to create a custom middleware in C#:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        // Perform some action before calling the next middleware
        Console.WriteLine("Custom middleware executing before the next middleware");

        // Call the next middleware in the pipeline
        await _next(context);

        // Perform some action after the next middleware has executed
        Console.WriteLine("Custom middleware executing after the next middleware");
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, we create a middleware component called CustomMiddleware that takes in a RequestDelegate parameter in its constructor. The RequestDelegate is a delegate that represents the next middleware in the pipeline.

The CustomMiddleware class also defines an InvokeAsync method, which is the method that is called when the middleware is executed. In this method, we perform some action before calling the next middleware, call the next middleware in the pipeline using the _next delegate, and then perform some action after the next middleware has executed.

To add this middleware to the pipeline, we can use the UseMiddleware extension method in the Startup class:

using Microsoft.AspNetCore.Builder;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<CustomMiddleware>();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we add the CustomMiddleware to the pipeline using the UseMiddleware method. Now, every time a request is received, the CustomMiddleware will execute before the next middleware in the pipeline.

Note that this is just a simple example of how to create and use a middleware in .NET Core. There are many built-in middlewares available in the framework that can be used for various purposes, and you can also create your own custom middlewares to handle specific tasks in your application.

Middlewares made code more easyand manageable :)

Top comments (0)