我最近接手了一个庞大的C#MVC项目。它本地化为英语和挪威语,但我在本地化方面存在一些问题,以及如何正确设置路线。我想要实现的目标如下:
对于所有情况,URL应保持不变。我是否需要为所有情况设置单独的非本地化路由,例如我为登录页面做过的事情?这是代码的主要部分:
routes.MapRoute(
name: "metaRelated",
url: "related/{type}/{id}",
defaults: new { controller = "Meta", action = "Related" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
name: "login",
url: "Login",
defaults: new { controller = "Login", action = "Login" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
name: "loginNoCulture",
url: "Login",
defaults: new { controller = "Login", action = "Login", culture = UrlParameter.Optional }
).RouteHandler = new MvcRouteHandler();
routes.MapRoute(
name: "actionStatus",
url: "DocumentActions/{ActionStatus}/{DocumentId}",
defaults: new { controller = "Action", action = "Index", DocumentId = UrlParameter.Optional }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MultiCultureMvcRouteHandler();
foreach (Route r in routes)
{
if (r.RouteHandler is MultiCultureMvcRouteHandler)
{
r.RouteHandler = new MultiCultureMvcRouteHandler();
r.Url = "{culture}/" + r.Url;
// Adding default culture
if (r.Defaults == null)
r.Defaults = new RouteValueDictionary();
r.Defaults.Add("culture", Culture.No.ToString().ToLower());
// Adding constraint for culture param
if (r.Constraints == null)
r.Constraints = new RouteValueDictionary();
r.Constraints.Add("culture", new CultureConstraint(Culture.En.ToString().ToLower(), Culture.No.ToString().ToLower(), Culture.Nl.ToString().ToLower()));
}
}
这是MultiCultureMvcRouteHandler类:
public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var culture = requestContext.RouteData.Values["culture"].ToString();
var ci = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
return base.GetHttpHandler(requestContext);
}
}