Middleware in .Net core

Middleware

In ASP.NET Core, middleware is software components that are added to the request pipeline to handle requests and responses. Middleware components are executed in the order they are added to the pipeline, and each component can process the request or response, perform some action, or modify the request or response before passing it to the next middleware in the pipeline.

Middleware components are added in the Startup.cs file in the Configure method. Here's a basic example of how middleware is added in an ASP.NET Core application:


   
  
  
public class Startup
{
    // Other configuration methods...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        
        // Custom middleware
        app.UseMyCustomMiddleware();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
  


In this example, you can see the usage of built-in middleware like UseDeveloperExceptionPage, UseExceptionHandler, UseHsts, UseHttpsRedirection, and UseStaticFiles. Additionally, there's a custom middleware named UseMyCustomMiddleware.

To create your own custom middleware, you need to create a class with a method that takes a HttpContext and a Func'' delegate as parameters. The custom middleware class might look like this:

   
  
  public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        // Do something before the next middleware
        await context.Response.WriteAsync("Custom Middleware: Before\r\n");

        await _next(context);

        // Do something after the next middleware
        await context.Response.WriteAsync("Custom Middleware: After\r\n");
    }
}
  
Then, in the Startup.cs file, add the following extension method to register your middleware:]


   
  
        public static class MyCustomMiddlewareExtensions
        {
            public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware();
            }
        }
 

Make sure to add the necessary using statements for the classes involved.

This is a simple example, and you can create more complex middleware based on your application's requirements. Middleware can be used for logging, authentication, authorization, compression, and many other purposes in an ASP.NET Core application.

Comments