为什么需要在 UseMvc() 中定义路由之前调用 UseRewriter()?

Why one needs to call UseRewriter() before defining routes in UseMvc()?

我创建了简单的重写器并在定义路由后调用了 app.UseRewriter

app.UseMvc(routes =>
            {...});
app.UserRewriter(new RequestCatcher());

这导致当我使用浏览器并转到:

仅当我在定义路由之前移动 app.UseRewriter(rewriteOptions); 调用时,所有请求都在 ApplyRule 方法中处理。这是为什么?

中间件按照注册顺序执行。如果你把它放在 UseMvc 之后,那么只有当 Mvc 处理它时,它才会被重写。但到那时,已经为时已晚,因为行动已经得到处理。

请参阅 Middlewares 文档。

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.