How C# ASP.NET Core Middleware is different from HttpModule?


HttpModules are configured via web.config or global.asax Developer don’t have control on order of execution.

As order of modules is mainly based on application life cycle events. The execution order remains same for requests and responses.

HttpModules helps you to attach code specific to a application events. HttpModules are tied to System.web.

Middleware are configured in Startup.cs code rather than web.config file (entry point for application)

Unlike HttpModules, there is full control of what get’s executed and in what order. As they are executed in the order in which they are added.

Order of middleware for responses is the reverse from that for requests.

Middleware is independent of these events.

Middlewares are host independent.

Built in Middlewares of Asp.Net core

Authentication    Provides authentication support.

CORS                  Configures Cross-Origin Resource Sharing.

Routing              Define and constrain request routes.

Session              Provides support for managing user sessions.

Diagnostics       Includes support for error pages and runtime information.

Example

public class MyMiddleware{
   private readonly RequestDelegate _next;
   private readonly ILogger _logger;
   public MyMiddleware(RequestDelegate next, ILoggerFactory logFactory){
      _next = next;
      _logger = logFactory.CreateLogger("MyMiddleware");
   }
   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 MyMiddlewareExtensions{
   public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder
   builder){
      return builder.UseMiddleware<MyMiddleware>();
   }
}

//add custom middleware in the request pipeline by using Use extension method as shown below

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
   app.UseMiddleware<MyMiddleware>()
   app.Run(async (context) =>{
      await context.Response.WriteAsync("Hello World!");
   });
}

Updated on: 25-Sep-2020

769 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements