Skip to content

Instantly share code, notes, and snippets.

@frankgeerlings
Created January 31, 2012 16:54
Show Gist options
  • Save frankgeerlings/1711560 to your computer and use it in GitHub Desktop.
Save frankgeerlings/1711560 to your computer and use it in GitHub Desktop.
Remove trailing slash in URLs with ASP.NET MVC routing
// Put this in Global.asax.cs
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();
}
}
@dementic
Copy link

Wouldn't url.ToLower().TrimEnd('/', '\\') be more clear of what you are trying to achieve ?

@bobparker58
Copy link

Try this:
var uri = Context.Request.Url.ToString();
if (UriHasRedundantSlashes(uri))
{
var correctUri = RemoveRedundantSlashes(uri);
Response.RedirectPermanent(correctUri);
}
}

private string RemoveRedundantSlashes(string uri)
{
    const string http = "http://";
    const string https = "https://";
    string prefix = string.Empty;

    if (uri.Contains(http))
    {
        uri = uri.Replace(http, string.Empty);
        prefix = http;
    }
    else if (uri.Contains(https))
    {
        uri = uri.Replace(https, string.Empty);
        prefix = https;
    }

    while (uri.Contains("//"))
    {
        uri = uri.Replace("//", "/");
    }

    if (!string.IsNullOrEmpty(prefix))
    {
        return prefix + uri;
    }
    return uri;
}

private bool UriHasRedundantSlashes(string uri)
{
    const string http = "http://";
    const string https = "https://";

    if (uri.Contains(http))
    {
        uri = uri.Replace(http, string.Empty);
    }
    else if (uri.Contains(https))
    {
        uri = uri.Replace(https, string.Empty);
    }
    return uri.Contains("//");
}

See: https://pro-papers.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment