这就是我修复项目的方式:
- 添加了一个将扩展 RazorViewEngine 的类(继承自它)。
我使用了 Brian Reiter 帖子(上面的链接)中的代码,稍作更改(从 WebFormsViewEngine 到 RazorViewEngine、我的应用程序文化 cookie 以及从文化中提取两个字母的语言):
使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Web;
使用 System.Web.Mvc;
使用 System.Text.RegularExpressions;
使用 System.IO;
使用 LeadsWize.Helpers;
使用 System.Globalization;
命名空间 System.Web.Mvc
{
公共类 GlobalizationViewEngine : RazorViewEngine
{
受保护的覆盖 IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
partialPath = GlobalizeViewPath(controllerContext, partialPath);
return new RazorView(controllerContext, partialPath, null, false, FileExtensions, ViewPageActivator);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
viewPath = GlobalizeViewPath(controllerContext, viewPath);
return base.CreateView(controllerContext, viewPath, masterPath);
}
private static string GlobalizeViewPath(ControllerContext controllerContext, string viewPath)
{
var request = controllerContext.HttpContext.Request;
string cultureName = null;
HttpCookie cultureCookie = request.Cookies["_culture"];
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
cultureName = request.UserLanguages != null && request.UserLanguages.Length > 0 ?
request.UserLanguages[0] : // obtain it from HTTP header AcceptLanguages
null;
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
var lang = (CultureInfo.CreateSpecificCulture(cultureName)).TwoLetterISOLanguageName; // this is to extract the two languge letters from the culture
if (lang != null &&
!string.IsNullOrEmpty(lang) &&
!string.Equals(lang, "en", StringComparison.InvariantCultureIgnoreCase))
{
string localizedViewPath = Regex.Replace(
viewPath,
"^~/Views/",
string.Format("~/Views/Globalization/{0}/",
lang
));
if (File.Exists(request.MapPath(localizedViewPath)))
{ viewPath = localizedViewPath; }
}
return viewPath;
}
}
}
-
在 Global.asxs.cs 的 Application_Stat 中添加了两行
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new GlobalizationViewEngine()); //this is our customized extended view engine to support the globaliztion in view folder Globalization.
** 请注意,全球化视图文件的文件夹 arangemnet 与 Brian 的帖子中的层次结构完全相同。