我相信有很多方法可以实现这一点,但您可以按照下面的方法进行操作。
首先,您可以通过在视图名称中添加文化后缀来假设视图的一些命名约定,即 ViewName_ en-US .cshtml、ViewName_ pl-PL .cshtml 等。
如果是这样,请不要根据当前文化在每个操作中分别构造这些名称。只需编写处理该问题的通用逻辑 - 具有覆盖OnActionExecuted
方法的基本控制器:
public class BaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var view = filterContext.Result as ViewResultBase;
if(view != null)
{
var viewName = string.IsNullOrEmpty(view.ViewName)
? filterContext.RouteData.Values["action"].ToString()
: view.ViewName; // retrieve the custom view name if provided or default action name otherwise
var cultureName = Thread.CurrentThread.CurrentUICulture.Name;
var localizedViewName = string.Format("{0}_{1}", viewName, cultureName); // construct composite, culture-aware name
if (ViewExists(localizedViewName)) // safety check in case not all your views are localized - if so, just return the default name
{
filterContext.Result = new ViewResult { ViewName = localizedViewName };
}
}
}
private bool ViewExists(string name)
{
var result = ViewEngines.Engines.FindView(ControllerContext, name, null);
return result.View != null;
}
}
操作现在不需要任何本地化处理:
public class HomeController : BaseController
{
public ActionResult AboutUs()
{
// (...) nothing special here
return View();
}
}