Adam
Adam

Reputation: 735

Remove Trailing Slash - Not using IIS rewrite ASP.net

How would I remove a trailing slash without using the IIS rewrite module?

I assume I can add something to the RegisterRoutes function in the global.asax.cs file?

Upvotes: 2

Views: 3431

Answers (2)

Chris
Chris

Reputation: 3298

Using an extension method on the HttpContext.Current.Request makes this reusable for other similar issues such as redirecting to avoid duplicate content URLs for page 1:

public static class HttpRequestExtensions
{
    public static String RemoveTrailingChars(this HttpRequest request, int charsToRemove)
    {
        // Reconstruct the url including any query string parameters
        String url = (request.Url.Scheme + "://" + request.Url.Authority + request.Url.AbsolutePath);

        return (url.Length > charsToRemove ? url.Substring(0, url.Length - charsToRemove) : url) + request.Url.Query;
    }
}

This can then be called as needed:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    String requestedUrl = HttpContext.Current.Request.Url.AbsolutePath;
    // If url ends with /1 we're a page 1, and don't need (shouldn't have) the page number
    if (requestedUrl.EndsWith("/1"))
        Response.RedirectPermanent(Request.RemoveTrailingChars(2));

    // If url ends with / redirect to the URL without the /
    if (requestedUrl.EndsWith("/") && requestedUrl.Length > 1)
        Response.RedirectPermanent(Request.RemoveTrailingChars(1));
}

Upvotes: 0

Adam
Adam

Reputation: 735

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // Do Not Allow URL to end in trailing slash
        string url = HttpContext.Current.Request.Url.AbsolutePath;
        if (string.IsNullOrEmpty(url)) return;

        string lastChar = url[url.Length-1].ToString();
        if (lastChar == "/" || lastChar == "\\")
        {
            url = url.Substring(0, url.Length - 1);
            Response.Clear();
            Response.Status = "301 Moved Permanently";
            Response.AddHeader("Location", url);
            Response.End();
        }
    }

Upvotes: 5

Related Questions