我会用它OnActionExecuting
来处理检索语言过程,例如:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
#region set Language
var lang = string.Empty;
if (filterContext.RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
{
// set the culture from the route data (url {lang})
lang = filterContext.RouteData.Values["lang"].ToString();
switch (lang)
{
case "es":
break;
case "en":
break;
default:
lang = "es";//default language
filterContext.RouteData.Values["lang"] = lang;
filterContext.HttpContext.Response.Redirect("/");
break;
}
}
else
{
//set default language
lang = "es";
filterContext.RouteData.Values["lang"] = lang;
}
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
#endregion
base.OnActionExecuting(filterContext);
}
然后在您的代码中的任何地方,您只需阅读Thread.CurrentThread.CurrentCulture
(这将是您的全局语言指示器)以显示正确的语言。
更新 - 知道我明白你的意思=)
如果页面将被动态创建,那么您将不会有ActionResult
每页,您只需要一个 ActionResult,例如:
public ActionResult ShowPage(int id,string slug)
{
//Use the slug to check for url attacks and ensure 301 redirections to the correct url
var page = db.Webpages_local.First(p=> p.id == id
&& p.culture.name == Thread.CurrentThread.CurrentCulture);
return View(page);
}
出于 SEO 原因,我建议您定义如下路线:
routes.MapRoute(
name: "LocalizedPages",
url: "{lang}/p/{slug}/{id}",
defaults: new { controller = "Page", action = "Show", id = UrlParameter.Optional },
constraints: new { lang = @"(es|en|fr|nl)" }
);
这会给你这样的网址:
/nl/p/about/1 //the p is just an identifier for 'page', to differentiate this routes from others