2014-01-20 25 views
2

我跟着this指南,它適用於我的語言支持。網址如 http://domain.com:33982/en-us/Test效果很好。ASP.Net MVC 5路由與文化的網址

但是,我的問題是,我希望它與 http://domain.com:33982/Test以及。我無法弄清楚如何路由它沒有文化的鏈接... 我在RouteConfig.cs路線

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

我真的不明白爲什麼它不工作。當我去/測試只是將我重定向到默認主頁/索引。

有什麼建議嗎?謝謝

+0

如果你不設置文化違約的默認路由嗎? –

+0

請參閱[ASP.NET MVC 5在路由和URL中的文化](http://stackoverflow.com/a/32839796/181087) – NightOwl888

回答

4

這是因爲第一和第二路線都匹配。可選參數使應用程序選擇匹配的第一個:所以第一個總是被選中。

試試這個:

 routes.MapRoute(name: "DefaultWithCulture" 
         , url: "{culture}/{controller}/{action}/{id}" 
         , defaults: new { culture = "en-us", controller = "Home", action = "Index", id = UrlParameter.Optional } 
         , constraints: new { culture = "[a-z]{2}-[a-z]{2}" } 
     ); 

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

它的工作原理在這裏(他們身後retulting文化):

http://host/ (en-us) 
http://host/Home/Index (xx-xx) 
http://host/zh-cn/Home/Index (zh-cn) 
+0

真的不想將Test(又名我的所有控制器的名稱)添加到route.cs 。真的想在這種情況下使用{controller}。 – robertk

+0

只是一個例子來向你展示匹配引擎是問題。你必須做一些事情來使路由引擎做出正確的決定。更新的例子。 –

+0

我看到你的例子,是不是有DefaultCulture的任何方式?我真的希望它與domain.com/{controller}一起工作,並且不希望它只是因爲文化不存在而重定向到錯誤頁面... – robertk