自定义中间件是在ASP.NET Core请求管道中处理请求和响应的组件,通过创建实现InvokeAsync方法并接收HttpContext的类,结合RequestDelegate调用下一个中间件,可实现日志、认证等跨切面逻辑;需在Program.cs中使用app.UseMiddleware<T>()注册,且顺序至关重要;推荐使用构造函数注入配置或单例服务,通过InvokeAsync参数注入作用域服务以避免生命周期错误,调试时应关注_next调用、异步await及中间件执行顺序。

在ASP.NET Core中,自定义中间件就是你在HTTP请求处理管道中插入的一段逻辑,它能拦截、检查、修改甚至终止请求,或者在请求处理完毕后对响应做些操作。这就像一个交通检查站,每个请求在到达最终目的地(你的控制器或最小API)之前,都必须经过它,你可以在这里做身份验证、日志记录、错误处理、请求限流等任何你想在请求流中统一处理的事情。
创建自定义中间件主要有两种方式,一种是直接在
Startup.cs
Program.cs
app.Use()
1. 创建自定义中间件类
一个典型的自定义中间件类需要满足以下条件:
RequestDelegate
InvokeAsync
Invoke
HttpContext
Task
让我们创建一个简单的日志记录中间件,它会在请求开始和结束时记录一些信息:
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Threading.Tasks;
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)
{
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation($"Request started: {context.Request.Method} {context.Request.Path}");
// 调用管道中的下一个中间件
await _next(context);
stopwatch.Stop();
_logger.LogInformation($"Request finished: {context.Request.Method} {context.Request.Path} in {stopwatch.ElapsedMilliseconds}ms. Status: {context.Response.StatusCode}");
}
}2. 注册和使用自定义中间件
在
Program.cs
Startup.cs
Configure
app.UseMiddleware<T>()
app.Use()
// Program.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// 在这里注册你的自定义中间件
// 注意:中间件的注册顺序至关重要!
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseAuthorization();
app.MapControllers();
app.Run();通过
app.UseMiddleware<RequestLoggingMiddleware>()
RequestLoggingMiddleware
这确实是个让人头疼的问题,因为ASP.NET Core提供了多种方式来处理请求。我的经验是,选择哪种方案,很大程度上取决于你的逻辑在“请求生命周期”中的位置和作用域。
中间件位于HTTP请求管道的最前端,或者说,它直接操作的是原始的
HttpContext
而过滤器(如Action Filter, Authorization Filter等)则更专注于MVC/API的特定阶段。它们是在某个控制器、某个Action方法,或者某个Razor Page执行前后插入逻辑。比如,你只想对某个特定的API方法进行参数验证、权限检查(基于角色或策略)、结果缓存,或者在Action执行前后修改Model或ViewData,那么过滤器更合适。它就像大楼里的“部门主管”,只负责自己部门的业务。它能访问到
ActionContext
ResultContext
至于服务,那更是应用程序的核心业务逻辑了。服务通常不直接参与请求管道的拦截和处理,而是被控制器、过滤器或中间件所调用,来完成具体的业务计算、数据存储等任务。它们是“大楼里的员工”,负责具体的工作。
简而言之:
HttpContext
ActionContext
当你发现你的逻辑需要作用于所有或大部分请求,并且不关心具体的控制器或Action时,中间件通常是更自然、更高效的选择。
在实际开发中,自定义中间件虽然强大,但也容易踩坑。我见过最常见的几个问题和相应的调试策略如下:
1. 中间件顺序问题
这是最容易让人迷惑的地方。ASP.NET Core的请求管道是线性的,中间件的注册顺序决定了它们的执行顺序。如果你的认证中间件放在授权中间件之后,那授权可能就无法正常工作了,因为它拿不到认证信息。同样,如果一个错误处理中间件放在了其他可能抛出异常的中间件之前,那它就无法捕获到后续中间件的异常。
调试策略:
InvokeAsync
InvokeAsync
HttpContext
_next(context)
2. _next(context)
忘记调用
await _next(context);
return
调试策略:
_next(context)
_next(context)
3. 异步操作处理不当
在
InvokeAsync
await
await
调试策略:
4. 依赖注入问题
中间件本身可能需要依赖其他服务。如果在构造函数中注入了生命周期不匹配的服务(比如在单例中间件中注入了作用域服务),或者在
InvokeAsync
调试策略:
Singleton
Scoped
Transient
InvokeAsync
InvokeAsync
InvokeAsync
在自定义中间件中集成依赖服务或配置,是实现其功能和灵活性的关键。这通常通过依赖注入(DI)机制来完成,但具体操作方式会因服务生命周期和中间件的实现方式而异。
1. 构造函数注入(Constructor Injection)
这是最常见和推荐的方式,适用于那些生命周期与中间件实例本身一致的服务。通常,中间件实例在应用程序启动时只创建一次(如果是单例),或者每次请求时创建一次(如果是通过
IMiddleware
// 注入日志服务和配置
public class MyCustomMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<MyCustomMiddleware> _logger;
private readonly MyCustomOptions _options; // 假设有一个配置类
public MyCustomMiddleware(RequestDelegate next, ILogger<MyCustomMiddleware> logger, IOptions<MyCustomOptions> options)
{
_next = next;
_logger = logger;
_options = options.Value; // 获取配置值
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation($"Middleware option value: {_options.SomeSetting}");
await _next(context);
}
}
// 对应的配置类
public class MyCustomOptions
{
public string SomeSetting { get; set; } = "Default Value";
}注册配置: 在
Program.cs
builder.Services.Configure<MyCustomOptions>(builder.Configuration.GetSection("MyCustomSection"));
// 假设appsettings.json中有这样的配置:
// "MyCustomSection": {
// "SomeSetting": "Hello from config!"
// }注意: 如果你在构造函数中注入了
Scoped
Transient
app.UseMiddleware<T>()
2. InvokeAsync
对于那些需要作用域(Scoped)生命周期的服务,或者你希望每次请求都获取到最新的服务实例时,最佳实践是在
InvokeAsync
InvokeAsync
// 假设有一个作用域服务
public interface IScopedService
{
string GetOperationId();
}
public class ScopedService : IScopedService
{
private readonly Guid _operationId = Guid.NewGuid();
public string GetOperationId() => _operationId.ToString();
}
// 在中间件中使用 InvokeAsync 参数注入
public class AnotherCustomMiddleware
{
private readonly RequestDelegate _next;
public AnotherCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IScopedService scopedService) // 在这里注入 IScopedService
{
context.Items["OperationId"] = scopedService.GetOperationId(); // 将服务数据存入HttpContext
_logger.LogInformation($"Operation ID for this request: {scopedService.GetOperationId()}");
await _next(context);
}
}注册作用域服务:
builder.Services.AddScoped<IScopedService, ScopedService>();
总结:
IOptions<T>
InvokeAsync
理解这两种注入方式的区别和适用场景,能让你更安全、高效地构建自定义中间件,并避免潜在的运行时问题。
以上就是ASP.NET Core中的自定义中间件是什么?如何创建?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号