【问题标题】:Redirect Rule to Url Rewrite .NET Core重定向规则到 URL 重写 .NET Core
【发布时间】:2020-12-20 01:14:29
【问题描述】:

我在 Startup.cs 中实现 AddRewrite 规则,如下所示:

var rewriteOptions = new RewriteOptions()
            .AddRewrite(@"^UserLogin/([0-9]+)/([_0-9a-zA-Z-]+)", "User/UserLogin?param1=$1&param2=$2", skipRemainingRules: true)
        app.UseRewriter(rewriteOptions);

这很好用,访问时 url 被正确重写:UserLogin/param1value/param2value

现在我想重定向旧的原始网址,我尝试了这个:

    var rewriteOptions = new RewriteOptions()
            .AddRedirect(@"^User/UserLogin?param1=([0-9]+)&param2=([_0-9a-zA-Z-]+)", "UserLogin/$1/$2", (int)HttpStatusCode.Redirect)
            .AddRewrite(@"^UserLogin/([0-9]+)/([_0-9a-zA-Z-]+)", "User/UserLogin?param1=$1&param2=$2", skipRemainingRules: true)
        app.UseRewriter(rewriteOptions);

但是我不能让它工作,我不能让新的 url 工作。

我在这里错过了什么?

【问题讨论】:

    标签: redirect .net-core url-rewriting


    【解决方案1】:

    首先,您的正则表达式中的? 需要转义为\?,因为?在正则表达式中表示匹配 0 次或 1 次。

    但即使这样也无济于事,因为根据 AddRedirect 方法的文档,它的作用是

    如果正则表达式匹配 HttpContext 的 PathString,则重定向请求

    由于路径字符串不包含查询字符串,它不会匹配。如果您查看the implementation source code

    ,这很明显

    不幸的是,该实现是内部的,因此您无法创建从 RedirectRule 继承的规则,但由于该实现是开源的,您可以复制该实现并创建您自己的与 url 和查询字符串匹配的重定向规则。

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      相关资源
      最近更新 更多