【问题标题】:Querystring issue with .Net Core url rewrite.Net Core url 重写的查询字符串问题
【发布时间】:2020-05-09 14:53:06
【问题描述】:

在 ASP.NET Core 中处理应用程序时我在尝试重写单个 url 时遇到问题,例如: https://localhost:44318/Details?content=My-url-to-rewrite&id=221 进入 https://localhost:44318/mypage

我在 Startup.cs 的 Configure() 方法开头使用的代码如下:

app.UseRewriter(new RewriteOptions()
        .AddRewrite(@"^Details?content=My-url-to-rewrite&id=221", "/mypage", skipRemainingRules: true));

奇怪的是,如果我尝试在没有查询字符串的情况下重写 url,如下所示,它可以工作

app.UseRewriter(new RewriteOptions()
        .AddRewrite(@"^Details", "/mypage", skipRemainingRules: true));

甚至添加问号来附加它的查询字符串,如下所示

app.UseRewriter(new RewriteOptions()
        .AddRewrite(@"^Details?", "/mypage", skipRemainingRules: true));

但是,只要我在问号后添加一个字符,url 就不会被重写,并且页面会像往常一样被链接,没有任何错误。

有什么想法吗?

提前致谢。

【问题讨论】:

    标签: asp.net-core url-rewriting


    【解决方案1】:

    您可以实现自己的重写中间件:

    Configure

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {   
        ....
        var options = new RewriteOptions()
                     .Add(RedirectMyRequests);
    
        app.UseRewriter(options);
        ...
    }
    static void RedirectMyRequests(RewriteContext context)
    {
        var request = context.HttpContext.Request;
        // Because we're redirecting back to the same app, stop processing if the request has already been redirected
        //If the modified path is similar with previous, add if statemetn to stop processing
    
        //check the request path and request QueryString
        if (request.Path.Value.StartsWith("/Details", StringComparison.OrdinalIgnoreCase) && request.QueryString.Value.StartsWith("?content", StringComparison.OrdinalIgnoreCase))
        {
            if (request.QueryString.Value.Split('&')[1].StartsWith("id", StringComparison.OrdinalIgnoreCase))
            {
                var response = context.HttpContext.Response;
                response.StatusCode = StatusCodes.Status301MovedPermanently;
                context.Result = RuleResult.EndResponse;
                //change it with needed path, it is combined with request path and request QueryString
                response.Headers[HeaderNames.Location] = "/Home/Privacy";
            }
    
        }
    }
    

    【讨论】:

    • 这个解决方案可以完成这项工作,但结果是“重定向”而不是“重写”,涉及使用客户端和更改浏览器栏中的原始 url。无论如何,管理请求的查询字符串值是一个很好的指示,我将尝试应用它以使其与适当的“重写”一起工作。非常感谢。
    • 查看c-sharpcorner.com/article/…并将您的逻辑写在ApplyRule
    猜你喜欢
    • 1970-01-01
    • 2011-08-02
    • 2012-01-18
    • 1970-01-01
    • 2014-08-07
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多