Remove trailing slash (/) at the end of Url

2 meses atrás
I have added code below to
NopStartup.cs 
remove more than 1 //// on the URL and it works perfectly fine.


public void Configure(IApplicationBuilder application)
{
     //var rewriteOptions = new RewriteOptions()
     //.AddRedirect(@"^(.*?)/{2,}$", "$1"); // Redirect URLs with multiple slashes to the normalized URL
    
     var rewriteOptions = new RewriteOptions()
    .AddRedirect(@"^(.*?)/{2,}$", "$1") // Redirect URLs with multiple slashes to normalized URL
    .Add(ctx =>
    {
        var request = ctx.HttpContext.Request;
        var originalPath = request.Path.Value;
        var path = originalPath;

        // Now, check for and remove trailing slash if not the root "/"
        // First, normalize the path: convert to lowercase.
        path = path.ToLowerInvariant();

        // Then, remove trailing slash if necessary. Apply this after converting to lowercase to ensure it's effective.
        var newPath = (path.Length > 1 && path.EndsWith("/")) ? path.TrimEnd('/') : path;


        // Only redirect if the new path is different from the original
        if (newPath != originalPath)
        {
            var newUrl = $"{newPath}{request.QueryString}";
            ctx.HttpContext.Response.Redirect(newUrl, permanent: true);
        }

    });

     application.UseRewriter(rewriteOptions);

     application.UseResponseCaching();
}


However, if the URL =
https://www/abc.com/product123/

It remains
https://www/abc.com/product123/

What is the issue why won't it remove the trailing / and any other solution?
2 meses atrás
I do notice that you only ToLowerInvariant() on path and not originalPath, which could lead to "false positive", but that should not fail your removal of extra "/".  So, set a breakpoint and debug/step through code.  Maybe it does get removed, but is somehow later "added back", or maybe the URL on the Store config is getting used.



2 meses atrás
Got tired of trying so I redirect :

public abstract partial class BasePublicController : BaseController
{
     public override void OnActionExecuting(ActionExecutingContext context)
     {
         base.OnActionExecuting(context);

         var path = context.HttpContext.Request.Path.Value;

         // Check if the URL ends with a slash and is longer than 1 character
         if (path.Length > 1 && path.EndsWith("/"))
         {
             // Remove the trailing slash
             var newPath = path.TrimEnd('/');

             // Reconstruct the URL without the trailing slash
             var newUrl = $"{context.HttpContext.Request.Scheme}://{context.HttpContext.Request.Host}{newPath}{context.HttpContext.Request.QueryString}";

             // Redirect permanently to the new URL
             context.Result = new RedirectResult(newUrl, permanent: true);
         }
     }


Works perfectly.