Home >Backend Development >C#.Net Tutorial >How is C# ASP.NET Core middleware different from HttpModule?

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

PHPz
PHPzforward
2023-08-28 10:21:10681browse

C# ASP.NET Core 中间件与 HttpModule 有何不同?

HttpModules configured through web.config or global.asax The developer has no control over the order of execution.

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

HttpModules help you attach code specific to application events. HttpModules are bound to System.web.

Middleware is configured in the Startup.cs code, not the web.config file (entry point For applications)

Unlike HttpModule, you can fully control the execution content and execution order of get. as They are executed in the order they are added.

The order of middleware responses is reversed from the order of requests.

Middleware is independent of these events.

Middleware is independent of the host.

Built-in Asp.Net core middleware

Authentication Provides authentication support.

CORS Configure cross-domain resource sharing.

Routing Define and limit request routing.

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 for adding 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 the extension method as As shown below

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

The above is the detailed content of How is C# ASP.NET Core middleware different from HttpModule?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete