中间件不按顺序执行

Middleware not executed depending on order

我知道中间件被注入中间件并被前面的同上。在每个过程中,我们可以调用 next() 并将接力棒传递给后续的内部软件。按照这种逻辑,顺序可能会影响应用程序的行为。但是,我看不出订单如何导致链条被破坏(除非发生异常或开发人员未能调用 next())。

我注意到以下命令(vanilla weather 项目)确实执行了两个中间件。

app.Use(async (context, next) => throw new Exception());
app.UseEndpoints(endpoints => endpoints.MapControllers());

当我切换顺序时,如下所示,只有UseEndPoints(...)被执行而Use(...)永远不会发生(根据一堆未命中的断点甚至没有抛出异常)。

app.UseEndpoints(endpoints => endpoints.MapControllers());
app.Use(async (context, next) => throw new Exception());

我发现 some info 与网络套接字有关,如果管道 运行 出现错误,则会出现错误。但是,这不会产生上述错误,也不会真正调用我的 vanilla 项目中的网络套接字。所以我觉得我还缺少其他东西。

...you must keep the middleware pipeline running for the duration of the connection. If you attempt to send or receive a WebSocket message after the middleware pipeline ends, you may get an exception...

原因在您的问题中提到:“开发人员未能调用 next()”,尽管在这种情况下它本身并不是失败,因为中间件本质上是管道的末端,如果它找到要执行的操作。

查看source