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

问题描述 投票:0回答:1

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

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
方法中处理。这是为什么?

.net asp.net-core url-rewriting routes startup
1个回答
1
投票

中间件按照注册的顺序执行。如果你把它放在

UseMvc
之后,那么只有 Mvc 确实处理了它,它才会被重写。但到那时,已经太晚了,因为行动已经处理完毕。

请参阅中间件文档。

在 Startup.Configure 方法中添加中间件组件的顺序定义了请求时调用中间件组件的顺序以及响应时的相反顺序。该顺序对于安全性、性能和功能至关重要。

© www.soinside.com 2019 - 2024. All rights reserved.