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(); | |
} | |
} |
Wouldn't url.ToLower().TrimEnd('/', '\\')
be more clear of what you are trying to achieve ?
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
MVC has a general issue with this if your webapplication is rooted at the URI authority. So:
http://www.google.com/
will become
httP://www.google.com
MVC will not attempt to run any default routes if this is the case. The modern browsers I've tested do append a trailing slash if missing from a URL authority. It appears to be because of HTTP/1.1 requirements:
http://stackoverflow.com/questions/11325425/remove-trailing-slash-in-asp-net-mvc-4-route-to-application-root
https://gist.github.com/AniAko/3f955b5ad9a71f17635e