为什么需要在 UseMvc() 中定义路由之前调用 UseRewriter()?
Why one needs to call UseRewriter() before defining routes in UseMvc()?
我创建了简单的重写器并在定义路由后调用了 app.UseRewriter
:
app.UseMvc(routes =>
{...});
app.UserRewriter(new RequestCatcher());
这导致当我使用浏览器并转到:
http:\localhost:5050\test
从不执行 ApplyRule 方法
http:\localhost:5050\test
只有对 css
、json
、js
等文件的请求才会在 ApplyRule
方法中被捕获和处理
public class RequestCatcher : IRule
{
public RequestCatcher()
{
}
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
if (request.Path.Value.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
}
}
}
仅当我在定义路由之前移动 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.
我创建了简单的重写器并在定义路由后调用了 app.UseRewriter
:
app.UseMvc(routes =>
{...});
app.UserRewriter(new RequestCatcher());
这导致当我使用浏览器并转到:
http:\localhost:5050\test
从不执行 ApplyRule 方法http:\localhost:5050\test
只有对css
、json
、js
等文件的请求才会在ApplyRule
方法中被捕获和处理public class RequestCatcher : IRule { public RequestCatcher() { } public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; if (request.Path.Value.EndsWith("/", StringComparison.OrdinalIgnoreCase)) { } } }
仅当我在定义路由之前移动 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.