Language in URL, Routing and Areas
I've learned so far how to set up a correct routing if I would like to have the language within the URL, e.g. .../en/MyController/MyMethod
. With the following routing this works great so far:
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",
});
Now I Inserted a new area Cms
, and I call AreaRegi开发者_如何学JAVAstration.RegisterAllAreas();
in Application_Start().
As soon as I call a controller within this area, I miss the language-key:
MvcHandler handler = Context.Handler as MvcHandler;
if (handler == null)
return;
string lang = handler.RequestContext.RouteData.Values["lang"] as string;
How could I make the above routing work with areas?
Thx for any tipps, sl3dg3
Check out the generated class that derives from AreaRegistration
, named [AreaName]AreaRegistration
.
It contains a route registration as well, this is the default:
context.MapRoute(
"AreaName_default",
"AreaName/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
The following routing works now in my case (the area is called 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" }
);
}
}
}
The only thing I'm not quite happy about: now I have more or less duplicate code in Global.asax and in this class. Is there a way to avoid these duplicate mappings?
精彩评论