目前,当我输入/ru/
时,它将更改为俄语,但如果我进入/
它将显示俄语资源(意味着设置了 cookie/区域设置),但它不会重定向到/ru/
. 我真的不能只是重定向它,例如,如果用户打开/en/item/32
并且他将语言更改为俄语,他需要重定向到/ru/item/32
,而不是/ru
.
我[Localization]
检查 cookie 的数据注释功能
public class Localization : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
{
// Set from route data
var lang = filterContext.RouteData.Values["lang"].ToString();
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
}
else
{
// Set from cookie
var cookie = filterContext.HttpContext.Request.Cookies["lang"];
var langHeader = string.Empty;
if (cookie != null)
{
langHeader = cookie.Value;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
else
{
// Cookie does not exist, set default
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
}
filterContext.RouteData.Values["lang"] = langHeader;
}
// Update cookie
HttpCookie _cookie = new HttpCookie("lang", Thread.CurrentThread.CurrentUICulture.Name);
_cookie.Expires = DateTime.Now.AddYears(1);
filterContext.HttpContext.Response.SetCookie(_cookie);
base.OnActionExecuting(filterContext);
}
}
我的路线是这样配置的
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Localization",
url: "{lang}/{controller}/{action}/{id}",
defaults: new { lang = "en", controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "ORMebeles.Controllers" }
);
/*
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "ORMebeles.Controllers" }
);
*/
}
}
那么我怎样才能将{lang}
属性注入到路由并让它粘在那里呢?