2013-04-21 53 views
2

如何從網站中的每個.aspx網頁中刪除.aspx?下面的工作,但只爲網站的根,並定義長文件夾結構是低效率和雜亂。從所有網頁中刪除.aspx

void RegisterRoutes(RouteCollection routes) 
{ 
    routes.MapPageRoute("RemASPx", "{file}", "~/{file}.aspx"); 
} 

void Application_Start(object sender, EventArgs e) 
{ 
    // Code that runs on application startup 
    RegisterRoutes(RouteTable.Routes); 
} 

下面的工作沒有結尾的斜線,但是我怎麼會強制它有尾隨斜線,因爲沒有任何東西可以遵循catch-all routeURL?

routes.MapPageRoute("RemASPx", "{*file}", "~/{file}.aspx"); 
+0

檢查了這一點:http://blog.stevensanderson.com/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/ – MUG4N 2013-04-21 09:30:05

+0

這可能有助於,雖然它沒有被標記爲接受http://forums.iis.net/t/1150350.aspx/2/10,並有這個博客http://www.hanselman.com/blog/IntroducingASPNETFriendlyUrlsCleanerURLsEasierRoutingAndMobileViewsForASPNETWebForms.aspx – christiandev 2013-04-21 09:50:50

+1

有趣的讀取這些指示我正確地重寫方向,就像在接受的答案中一樣。 – user2303264 2013-04-21 11:29:57

回答

3

保持該路由設置:

void RegisterRoutes(RouteCollection routes) 
{ 
    routes.MapPageRoute("RemoveASPx", "{*file}", "~/{file}.aspx"); 
} 

void Application_Start(object sender, EventArgs e) 
{ 
    RegisterRoutes(RouteTable.Routes); 
} 

添加此重寫:

protected void Application_BeginRequest(object sender, EventArgs e) 
{ 
    string url = HttpContext.Current.Request.Url.AbsolutePath; 
    if (string.IsNullOrEmpty(url) || 
     System.IO.Directory.Exists(Server.MapPath(url))) 
     return; 

    if (url.EndsWith("/")) 
    { 
     Response.Clear(); 
     Response.Status = "301 Moved Permanently"; 
     Response.AddHeader("Location", url.Substring(0, url.Length - 1)); 
     Response.End(); 
    } 
} 

上面的代碼塊:

  1. 檢查,如果該URL爲null或空自 - 理由
  2. 檢查URL是否爲目錄,因爲您不想重寫目錄(如果應用程序默認狀態中有任何內容會導致重定向循環,因爲將尾部斜槓添加到目錄中)
  3. 檢查URL以斜線結尾,因此如果需要刪除
  4. 301響應使用(最適合的響應 - 尤其是對於SEO);添加標題引起重定向