2012-10-19 30 views
1

因此,我試圖在我的URL中使用連字符以提高可讀性,但到目前爲止還沒有找到使其與mvc4協同工作的方法。URL中的MVC4連字符

我會在控制器代碼開始:

public ViewResult Index() 
    { 
     ViewBag.URL = Functions.fetchURL(); 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(LogonModel model, string returnUrl) 
    { 
     //omitted to save space 

     return View(model); 
    } 


    public ActionResult Forgot_Login_Info() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Forgot_Login_Info(RetrievePasswordViewModel model) 
    { 
     //omitted to save space 
     return View(); 

    } 

所以我用下劃線爲所看到與「Forgot_Login_Info」動作的名稱,這是該視圖的名稱,以及。爲了測試我還可以手動創建了一個名爲「忘記 - 登錄信息」

視圖在我的global.asax.cs文件我只是有這一行的路線

RouteConfig.RegisterRoutes(RouteTable.Routes); 

這是標準的路由符合新項目爲MVC4,這是掛鉤到「RouteConfig.cs」文件,並在該文件中這裏是我有的代碼,我發現在這個網站的另一個問題。

public class RouteConfig 
{ 
    public class HyphenatedRouteHandler : MvcRouteHandler 
    { 
     protected override IHttpHandler GetHttpHandler(RequestContext requestContext) 
     { 
      requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-","_"); 
      requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_"); 
      return base.GetHttpHandler(requestContext); 
     } 
    } 



    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 



     routes.Add(
     new Route("{controller}/{action}/{id}", 
     new RouteValueDictionary(
      new { controller = "Default", action = "Index", id = UrlParameter.Optional }), 
      new HyphenatedRouteHandler()) 
     ); 
    } 
} 

最後這裏是「索引」的觀點,這是我有一個鏈接到「Forgot_Login_Info」的代碼。

<div class="centerBlockItem" style="width:450px; text-align:center"> 
@Html.ActionLink("Forgot Password?", "Forgot-Login-Info") 
    @Html.ActionLink("Forgot Password?", "Forgot_Login_Info") 
</div> 

現在我有鏈接2種方式,1使用下劃線和其他使用連字符。根據我讀過的關於我爲此目的找到的代碼,兩個鏈接都應該打開「Forgot_Login_Info」視圖,而不是「Forgot-Login-Info」視圖。但是我得到的是第二個鏈接正常工作,並且動作名稱與視圖文件名稱匹配。但是當我點擊第一個鏈接時,我得到了一個404錯誤,因爲系統找不到「忘記登錄信息」視圖文件,即使我手動創建了一個名稱爲該文件名的文件進行測試。

還有一兩件事要注意,在我routeconfig文件中的代碼,在回答我發現了它建議我註釋掉默認路由代碼行和剛剛離開:

routes.Add(
     new Route("{controller}/{action}/{id}", 
     new RouteValueDictionary(
      new { controller = "Default", action = "Index", id = UrlParameter.Optional }), 
      new HyphenatedRouteHandler()) 
     ); 

我已經做到了這一點也和得到了同樣的結果。任何想法,我搞砸了?

+0

這是一種替代方法:http://mvccoderouting.codeplex.com/wikipage?title=Route+Formatting –

回答

0

好吧我想出了我做錯了什麼,我有這根據routebundle.cs文件根目錄下列出,但我試圖讓這項工作在一個地區,一旦我將此代碼移到區域註冊文件,它的工作像一個魅力。如果有人需要我的完整代碼清單,只需詢問,我會將其全部發布。

0

這是如何幫助搜索引擎優化,當抓取工具仍然可以訪問控制器的下劃線版本,從而複製內容。目前正在爲此苦苦掙扎。