2012-01-31 66 views
2

如何在不使用IIS重写模块的情况下删除尾部斜杠?删除拖尾斜杠 - 不使用IIS重写ASP.net

我假设我可以在global.asax.cs文件的RegisterRoutes函数中添加一些东西?

+0

有趣的是,如果你在这里搜索“url trailing slash”(在右上角的搜索框中输入,没有引号),一半的人想删除斜线,一半的人w蚂蚁添加它。 – DOK 2012-01-31 16:20:36

回答

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(); 
     } 
    } 
+2

如果你在localhost中测试,确保使用if(string.IsNullOrEmpty(url)|| url.Length == 1)return;这是因为第一个url只是“/” – danpop 2012-12-20 12:47:32

0

使用的HttpContext.Current.Request扩展方法使得这种可重复使用其他类似的问题,如重新定向,以避免重复内容的网址为第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; 
    } 
} 

这可以被称为需要:

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