如何在此代码中将默认文化添加到RouteValueDictionary():r.Defaults.Add(" culture"," sv"):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
foreach(var r in from Route r in routes where !(r.RouteHandler is SingleCultureRouteHandler) select r)
{
r.RouteHandler = new MultiCultureRouteHandler();
r.Url = "{culture}/" + r.Url;
// Adding default culture
if(r.Defaults == null)
{
r.Defaults = new RouteValueDictionary();
}
r.Defaults.Add("culture", "sv");
// Adding constraint for culture param
if(r.Constraints == null)
{
r.Constraints = new RouteValueDictionary();
}
r.Constraints.Add("culture", new UserRouteConstraint("en", "sv"));
}
这样:r.Defaults.Add("culture", HttpContext.Current.Request.UserLanguages[0].Substring(0, 2))
收到以下错误消息:"请求在此上下文中不可用"。
提前致谢!
答案 0 :(得分:1)
伟大的解决方案是ActionFilterAttribute:
routes.MapRoute(
name: "culture",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { culture = new UserRouteConstraint() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
和
public class LocalizationAttribute : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var culture = filterContext.RouteData.Values["culture"] as string;
var userLanguage = HttpContext.Current.Request.UserLanguages;
CultureInfo cultureInfo = new CultureInfo(culture ?? (userLanguage != null ? userLanguage[0].Substring(0, 2) : "sv"));
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
base.OnActionExecuting(filterContext);
}
}