【发布时间】:2021-03-14 04:01:23
【问题描述】:
如果我创建一个空白的 ASP.net Web Core Application,然后将 Startup.cs 中的 Configure() 方法替换为以下方法,则每个 Use() 和 Run() 操作都会调用两次。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int i = 0;
});
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int j = 0;
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
}
所以操作顺序是:
- 在第一个app.Use()中,调用了await next.Invoke()
- 在第二个app.Use()中,等待next.Invoke()被调用
- App.Run() 被调用
然后,它通过管道返回..
- 在第二个app.Use()中,调用了int j = 0
- 在第一个 app.Use() 中,调用了 int i = 0
所有这些都是预期的,因为它通过中间件并返回。但随后,上述每个步骤都将再次重复。
为什么每个中间件组件被调用两次?
【问题讨论】:
标签: c# .net asp.net-core