qidao123.com技术社区-IT企服评测·应用市场

标题: 了解 ASP.NET Core 中的中间件 [打印本页]

作者: 王柳    时间: 2025-1-11 18:48
标题: 了解 ASP.NET Core 中的中间件
在 .NET Core 中,中间件(Middleware) 是处理 HTTP 请求和响应的核心组件。它们被组织成一个请求处理管道,每个中间件都可以在请求到达终极处理程序之前或之后执行操纵。中间件可以用于实现各种功能,如身份验证、路由、日志记载、非常处理、静态文件服务等。
什么是中间件?

中间件是 HTTP 请求管道中的一个处理单元,负责处理传入的 HTTP 请求和返回的 HTTP 响应。每个中间件都有以下职责:
中间件的工作原理

中间件的工作原理可以概括为以下几个步骤:
常见的中间件及其工作原理

以下是一些常见的中间件及其工作原理:
1. 身份验证中间件(Authentication Middleware)

示例
  1. public void Configure(IApplicationBuilder app)
  2. {
  3.     app.UseAuthentication(); // 启用身份验证
  4.     app.UseAuthorization();  // 启用授权
  5. }
复制代码
2. 路由中间件(Routing Middleware)

示例
  1. public void Configure(IApplicationBuilder app)
  2. {
  3.     app.UseRouting(); // 启用路由解析
  4.     app.UseEndpoints(endpoints =>
  5.                      {
  6.                          endpoints.MapControllerRoute(
  7.                              name: "default",
  8.                              pattern: "{controller=Home}/{action=Index}/{id?}");
  9.                      });
  10. }
复制代码
3. 静态文件中间件(Static Files Middleware)

示例
  1. public void Configure(IApplicationBuilder app)
  2. {
  3.     app.UseStaticFiles(); // 启用静态文件服务
  4. }
复制代码
4. 非常处理中间件(Exception Handling Middleware)

示例
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3.     if (env.IsDevelopment())
  4.     {
  5.         app.UseDeveloperExceptionPage(); // 开发环境:显示详细错误页面
  6.     }
  7.     else
  8.     {
  9.         app.UseExceptionHandler("/Home/Error"); // 生产环境:重定向到错误页面
  10.     }
  11. }
复制代码
5. 日志记载中间件(Logging Middleware)

示例
  1. public class LoggingMiddleware
  2. {
  3.     private readonly RequestDelegate _next;
  4.     private readonly ILogger<LoggingMiddleware> _logger;
  5.     public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
  6.     {
  7.         _next = next;
  8.         _logger = logger;
  9.     }
  10.     public async Task InvokeAsync(HttpContext context)
  11.     {
  12.         _logger.LogInformation($"Request: {context.Request.Method} {context.Request.Path}");
  13.         await _next(context);
  14.         _logger.LogInformation($"Response: {context.Response.StatusCode}");
  15.     }
  16. }
复制代码
自定义中间件

你可以创建自定义中间件来处理特定的需求。自定义中间件通常是一个类,它包含一个 Invoke 或 InvokeAsync 方法,该方法接收 HttpContext 和一个 RequestDelegate 参数。
示例:
  1. public class CustomMiddleware
  2. {
  3.     private readonly RequestDelegate _next;
  4.     public CustomMiddleware(RequestDelegate next)
  5.     {
  6.         _next = next;
  7.     }
  8.     public async Task InvokeAsync(HttpContext context)
  9.     {
  10.         // 在调用下一个中间件之前执行的操作
  11.         await context.Response.WriteAsync("Custom Middleware: Before\n");
  12.         // 调用下一个中间件
  13.         await _next(context);
  14.         // 在调用下一个中间件之后执行的操作
  15.         await context.Response.WriteAsync("Custom Middleware: After\n");
  16.     }
  17. }
复制代码
然后在 Startup.cs 中使用这个中间件:
  1. public void Configure(IApplicationBuilder app)
  2. {
  3.     app.UseMiddleware<CustomMiddleware>();
  4.     // 其他中间件
  5.     app.UseRouting();
  6.     app.UseEndpoints(endpoints =>
  7.                      {
  8.                          endpoints.MapGet("/", async context =>
  9.                          {
  10.                              await context.Response.WriteAsync("Hello World!");
  11.                          });
  12.                      });
  13. }
复制代码
总结

通过理解中间件的工作原理和常见应用场景,你可以更好地计划和优化 .NET Core 应用程序的请求处理流程。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4