2011-03-17 96 views
1

到目前爲止,我學到了如何設置正確的路由,如果我想在URL中使用該語言,例如.../en/MyController/MyMethod。用下面的路由這個偉大的工程至今:URL,路由和區域中的語言

 routes.MapRoute("Default with language", "{lang}/{controller}/{action}/{id}",  
     new 
     { 
      controller = "Report", 
      action = "Index", 
      id = UrlParameter.Optional, 
     }, new { lang = "de|en" }); 
     // Standard-Routing 
     routes.MapRoute("Default", "{controller}/{action}/{id}", new 
     { 
      controller = "Report", 
      action = "Index", 
      id = UrlParameter.Optional, 
      lang = "de", 
     }); 

現在我插入一個新的領域Cms,我呼籲AreaRegistration.RegisterAllAreas();中的Application_Start()。

只要我把這個區域內的控制器,我錯過了語言的關鍵:

 MvcHandler handler = Context.Handler as MvcHandler; 
     if (handler == null) 
      return; 

     string lang = handler.RequestContext.RouteData.Values["lang"] as string; 

我如何才能與區域上面的路由工作?

THX任何的竅門,sl3dg3

回答

0

以下路由現在的作品在我的情況(該區域被稱爲Cms):

using System.Web.Mvc; 

namespace MyProject.Areas.Cms 
{ 
    public class CmsAreaRegistration : AreaRegistration 
    { 
     public override string AreaName 
     { 
      get 
      { 
       return "Cms"; 
      } 
     } 

     public override void RegisterArea(AreaRegistrationContext context) 
     { 

     context.MapRoute("Cms_default_with_language", "Cms/{lang}/{controller}/{action}/{id}", new 
     { 
      controller = "Home", 
      action = "Index", 
      id = UrlParameter.Optional, 
      lang = "de", 
     }, new { lang = "de|en" }); 
     context.MapRoute(
      "Cms_default", 
      "Cms/{controller}/{action}/{id}", 
      new { action = "Index", id = UrlParameter.Optional, lang = "de" } 
     ); 

     } 
    } 
} 

唯一我並不高興:現在我在Global.asax和這個類中有或多或少的重複代碼。有沒有辦法避免這些重複的映射?

+0

我不認爲它是用這樣的更新來回答你自己的問題。不管怎麼說,我認爲你的Area路由註冊需要'AreaRegistration'中的'AreaName',這就是爲什麼它需要在那裏覆蓋。 – 2011-03-17 13:49:11

+1

@Mike,爲什麼不回答我自己的問題?基本上它構成了我的答案的完整解決方案。 – sl3dg3 2011-03-17 14:33:54

1

退房生成的類,從AreaRegistration導出,命名[AreaName]AreaRegistration

它包含了一個路線登記爲好,這是默認的:

context.MapRoute(
    "AreaName_default", 
    "AreaName/{controller}/{action}/{id}", 
    new { action = "Index", id = UrlParameter.Optional } 
);