2

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?

1
  • 1
    Funny, if you search here for "url trailing slash" (enter that in the search box in the upper right, without the quotes), half the people want to remove the slash and half of them want to add it. Commented Jan 31, 2012 at 16:20

2 Answers 2

5
    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();
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

If you test in localhost, make sure to use if (string.IsNullOrEmpty(url) || url.Length == 1) return; This is because the first url is just "/"
0

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.