自定义中间件用于处理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();
传递参数给中间件
如果需要配置选项,可以结合依赖注入传入服务或配置对象。
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();
基本上就这些。自定义中间件是构建可复用请求处理逻辑的核心方式,理解其执行顺序和生命周期有助于写出高效、清晰的管道逻辑。不复杂但容易忽略的是构造函数参数限制和作用域服务的正确使用。
以上就是ASP.NET Core 中的自定义中间件如何编写?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1440999.html
微信扫一扫
支付宝扫一扫