第七章 中间件和请求管道

7.1 中间件基础

什么是中间件

中间件是ASP.NET Core应用程序请求处理管道中的软件组件。每个中间件执行特定任务,如路由、认证、异常处理等,并决定是否将请求传递给管道中的下一个中间件。

中间件的关键特点:

  • 可以处理传入的HTTP请求
  • 可以处理传出的HTTP响应
  • 可以选择是否将请求传递给下一个中间件
  • 可以在下一个中间件前后执行逻辑
  • 可以短路请求管道

常用内置中间件

ASP.NET Core提供了许多内置中间件组件:

var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

7.2 自定义中间件

创建中间件

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestLoggingMiddleware> _logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _logger.LogInformation($"Processing request: {context.Request.Method} {context.Request.Path}");

        await _next(context);

        _logger.LogInformation($"Finished processing request: {context.Response.StatusCode}");
    }
}

// 注册中间件
app.UseMiddleware<RequestLoggingMiddleware>();

wechat_2025-07-31_105805_938

posted @ 2025-08-07 09:10  高宏顺  阅读(255)  评论(0)    收藏  举报