ZetCode

ASP.NET UseMiddleware

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 UseMiddleware 方法。中间件构成了 ASP.NET Core 应用程序请求处理的骨干。

ASP.NET Core 中间件是组成请求和响应处理管道的组件。每个中间件都可以在下一个组件之前和之后处理请求。

基本定义

ASP.NET Core 中的中间件是组装到应用程序管道中的软件,用于处理请求和响应。每个组件都可以选择是否将请求传递给下一个组件。

UseMiddleware 扩展方法将中间件组件添加到应用程序管道。中间件按照添加到管道的顺序执行。

中间件可以在管道中的下一个组件之前和之后执行操作。它们还可以通过不调用下一个中间件来截断管道。

ASP.NET UseMiddleware 示例

以下示例演示了如何在 ASP.NET 8 中创建和使用自定义中间件。

Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseMiddleware<RequestTimingMiddleware>();
app.UseMiddleware<CustomHeaderMiddleware>();

app.MapGet("/", () => "Hello from ASP.NET Core!");

app.Run();

这会设置一个 ASP.NET 应用程序,其中包含两个自定义中间件组件。中间件将处理应用程序的所有请求。

Middleware/RequestTimingMiddleware.cs
public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestTimingMiddleware> _logger;

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

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();
        
        try
        {
            await _next(context);
        }
        finally
        {
            stopwatch.Stop();
            _logger.LogInformation(
                "Request {Method} {Path} took {ElapsedMilliseconds}ms",
                context.Request.Method,
                context.Request.Path,
                stopwatch.ElapsedMilliseconds);
        }
    }
}

此中间件测量并记录处理每个请求所花费的时间。它使用 Stopwatch 类来跟踪调用下一个中间件之前和之后的经过时间。

Middleware/CustomHeaderMiddleware.cs
public class CustomHeaderMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.OnStarting(() =>
        {
            context.Response.Headers.Add(
                "X-Custom-Header", 
                "Middleware-Example");
            return Task.CompletedTask;
        });

        await _next(context);
    }
}

此中间件将自定义标头添加到所有响应中。它演示了如何在管道的其余部分处理完请求后修改响应。

RequestTimingMiddleware 展示了如何通过包装 _next 调用来测量请求处理时间。CustomHeaderMiddleware 使用 OnStarting 回调演示响应修改。

中间件组件通过 Program.cs 中的 UseMiddleware<T>() 添加到管道中。它们按照注册的顺序执行,形成一个处理步骤管道。

来源

Microsoft ASP.NET 中间件文档

在本文中,我们探讨了 ASP.NET 8 中的 UseMiddleware 方法。中间件以模块化的方式提供了强大的能力来处理 HTTP 请求和响应。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面有十多年的经验。

列出所有 ASP.NET 教程