自定义中间件用于处理HTTP请求响应逻辑,需包含RequestDelegate构造函数及InvokeAsync方法,通过UseMiddleware注册,可结合DI传递参数或实现IMiddleware接口以支持依赖作用域服务。

在 ASP.NET Core 中,自定义中间件用于处理 HTTP 请求和响应管道中的逻辑,比如日志记录、身份验证、异常处理等。编写自定义中间件非常灵活,可以通过类或内联方法实现,推荐使用类的方式以提高可维护性。
自定义中间件的基本结构
一个典型的中间件类包含以下要素:
- 构造函数接收下一个中间件委托 RequestDelegate
- 必须有一个名为 Invoke 或 InvokeAsync 的公共方法,返回 Task
- 在 Invoke 方法中编写业务逻辑,并调用 _next(context) 继续执行管道
示例:记录请求耗时的中间件
public class RequestTimeMiddleware
{
private readonly RequestDelegate _next;
public RequestTimeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var startTime = DateTime.Now;
await _next(context); // 继续执行后续中间件
var endTime = DateTime.Now;
var duration = endTime - startTime;
Console.WriteLine($"请求 {context.Request.Path} 耗时: {duration.TotalMilliseconds}ms");
}}
在程序中注册中间件
要使用自定义中间件,需在 Program.cs 的 UseMiddleware() 方法中注册。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware();
app.MapGet("/", () => "Hello World!");
app.Run();
传递参数给中间件
如果需要配置选项,可以结合依赖注入传入服务或配置对象。
C#开的网站购物交易系统
一个用C#开的网站购物交易系统,带源码仅供学习参考,应用了WebCalendar控件。后台登陆帐号和密码分别为:admin admin WebCalendar控件是一个ASP.Net Web应用程序的日期控件,您可以通过设置控制控件中不同部分的样式的属性,来自定义 WebCalendar 控件的外观和图片;支持手动输入日期,支持输入时间,不会被TextBox,DropDownList遮挡。并且她是
下载
public class CustomHeaderMiddleware
{
private readonly RequestDelegate _next;
private readonly string _headerValue;
public CustomHeaderMiddleware(RequestDelegate next, string headerValue)
{
_next = next;
_headerValue = headerValue;
}
public async Task InvokeAsync(HttpContext context)
{
context.Response.Headers["X-Custom-Header"] = _headerValue;
await _next(context);
}}
由于中间件构造函数不能直接接收非服务参数,可通过扩展方法封装:
public static class CustomHeaderExtensions
{
public static IApplicationBuilder UseCustomHeader(
this IApplicationBuilder builder, string value)
{
return builder.UseMiddleware(value);
}
}
然后在 Program.cs 中使用:
app.UseCustomHeader("MyValue");
使用工厂模式创建中间件(高级)
若中间件需要依赖作用域服务,可使用 IMiddleware 接口,由容器管理生命周期。
public class ScopedLoggingMiddleware : IMiddleware
{
private readonly ILogger _logger;
public ScopedLoggingMiddleware(ILogger logger)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
_logger.LogInformation("请求开始: {Path}", context.Request.Path);
await next(context);
_logger.LogInformation("请求结束: {Path}", context.Request.Path);
}
}
注册时需将中间件类型添加到服务容器:
builder.Services.AddTransient();
// ...
app.UseMiddleware();
基本上就这些。自定义中间件是构建可复用请求处理逻辑的核心方式,理解其执行顺序和生命周期有助于写出高效、清晰的管道逻辑。不复杂但容易忽略的是构造函数参数限制和作用域服务的正确使用。









