2011-03-17 72 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 } 
);