Created
January 31, 2012 16:54
-
-
Save frankgeerlings/1711560 to your computer and use it in GitHub Desktop.
Remove trailing slash in URLs with ASP.NET MVC routing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
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("//");
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wouldn't
url.ToLower().TrimEnd('/', '\\')
be more clear of what you are trying to achieve ?