2012-01-31 84 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)); 
}