在ASP.NET Core中,可以使用Func
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
IGreeter greeter,
ILogger<Startup> logger)
{
// Outer delegate
app.Use((next) =>
{
// Inner delegate
return async (context) =>
{
logger.LogInformation("Request incoming");
if (context.Request.Path.StartsWithSegments("/mym"))
{
await context.Response.WriteAsync("Hit!!");
logger.LogInformation("Request handled");
}
else
{
await next(context);
logger.LogInformation("Request outgoing");
}
};
});
}
“使用”方法在框架中实现如下:
public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
{
_components.Add(middleware);
return this;
}
至少有一个内部调用的框架函数“ Build”,用于构建依赖项:
public RequestDelegate Build()
{
RequestDelegate app = context =>
{
// Implicitly execute matched endpoint at the end of the pipeline instead of returning 404
var endpointRequestDelegate = context.GetEndpoint()?.RequestDelegate;
if (endpointRequestDelegate != null)
{
return endpointRequestDelegate(context);
}
context.Response.StatusCode = 404;
return Task.CompletedTask;
};
foreach (var component in _components.Reverse())
{
app = component(app);
}
return app;
}
在foreach部分中,它循环遍历“ Use”函数内的所有外部函数,并将内部委托作为参数传递给它。 当应用程序启动时,外部函数仅被调用一次。在每个HTTP请求中都会调用内部委托。
我的问题是:内部委托人如何知道/记住其“下一个”对象? 在代码中似乎很明显,因为内部委托是在外部委托中调用的,因此它可以访问“下一个”对象。但是如何在内部实现?