从 URL .Netcore 中删除尾随 /

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

我正在尝试从 URL 中删除尾随 /,但似乎没有任何效果,我的代码确实在最后删除了多个 slases,所以:

https://www/abc.com/xxx////  becomes https://www/abc.com/xxx

但是

https://www/abc.com/xxx/ stays https://www/abc.com/xxx/

下面是我的代码,还提到尝试了很多事情,并且规则的顺序每次仍然相同:

 var rewriteOptions = new RewriteOptions()
 .Add(ctx =>
{
    var request = ctx.HttpContext.Request;
    var path = request.Path.Value;

    if (path.Length > 1 && path.EndsWith("/"))
    {
        path = path.TrimEnd('/');
    }

    // Check if URL is not already lowercase
    if (path.ToLowerInvariant() != path)
    {
        // Convert to lowercase
        var newPath = path.ToLowerInvariant();
        var newUrl = $"{newPath}{request.QueryString}";
        ctx.HttpContext.Response.Redirect(newUrl, permanent: true);
    }
})
.AddRedirect(@"^(.*?)/{2,}$", "$1");

 application.UseRewriter(rewriteOptions);

 application.UseResponseCaching();

谢谢你

c# .net .net-core url-rewriting
1个回答
0
投票

您可以在找到真实字符时使用循环。


static string trimTrailingSlash(string url)
{
    while (url.EndsWith("/")) //This is the loop which we use to trim the end.
    {
        url = url.TrimEnd('/'); //Trim the last charecter
    }
    return url;
}


//call the method
trimTrailingSlash("https://www/abc.com/xxx////") //becomes https://www/abc.com/xxx
trimTainlingSlash("https://www/abc.com/xxx/") //stays https://www/abc.com/xxx/
© www.soinside.com 2019 - 2024. All rights reserved.