URL,路由和区域中的语言

时间:2011-03-17 11:57:34

标签: c# asp.net-mvc-3 routing

到目前为止,我已经了解了如果我想在网址中使用该语言,如何设置正确的路由,例如.../en/MyController/MyMethod。通过以下路由,到目前为止效果很好:

        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,并在Application_Start()中调用了AreaRegistration.RegisterAllAreas();

一旦我在这个区域内呼叫控制器,我就会错过语言密钥:

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

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

如何使上述路由适用于区域?

任何tipps的thx,sl3dg3

2 个答案:

答案 0 :(得分:1)

查看从AreaRegistration派生的生成的类,名为[AreaName]AreaRegistration

它也包含路由注册,这是默认设置:

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

答案 1 :(得分: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和这个类中有或多或少的重复代码。有没有办法避免这些重复的映射?