【发布时间】:2026-01-28 02:40:01
【问题描述】:
我是 asp.net core 的新手,如果我的问题听起来很愚蠢,我很抱歉。在 asp.net core 3 中,我们可以实现一个自定义中间件,如下所示:
public class CustomMiddleware
{
private RequestDelegate next;
public CustomMiddleware (RequestDelegate nextDelegate) {
next = nextDelegate;
}
public async Task Invoke(HttpContext context) {
...
}
}
所以我们的自定义中间件不需要实现诸如IMiddleware 之类的接口或从抽象的中间件基类继承,这对我来说有点奇怪。因为对于控制器之类的其他东西,我们有public class HomeController : ControllerBase。那么为什么微软不为自定义中间件设置强类型接口/抽象类,例如,
public abstract class BaseMiddleware {
public BaseMiddleware(RequestDelegate nextDelegate) {
next = nextDelegate;
}
public abstract async Task Invoke(HttpContext context);
}
这样我们的自定义中间件就可以:
public class CustomMiddleware : BaseMiddleware
{
public CustomMiddleware(RequestDelegate nextDelegate) : base(nextDelegate) {}
public override async Task Invoke(HttpContext context) {
...
}
}
【问题讨论】:
-
如果 MS 按照您建议的方式完成,您无法在 Invoke 方法中注入服务,因为它的签名将被修复。
标签: c# asp.net-core middleware