我正在将全球化添加到C# MVC 5 web应用程序中。在大多数视图中,我使用的是参考资料,它工作得很好。对于具有大量自定义的视图,我想分离视图,每个视图用于不同的语言。我跟着Brian 帖子。我添加了视图下的全球化禁止器、ISO 639-1双字母宏语言代码以及特定langague的主文件夹和索引视图。
我理解我需要修改呈现视图的mechnisem,以考虑客户端的区域设置。在Brian的文章中,它是在web表单上演示的,在我的解决方案中,我似乎没有他的示例中的相同的WebFormViewEngine。
如果您可以指导我如何扩展和mvc视图引擎,那么正确的视图将根据地区呈现。
谢谢。
发布于 2014-02-20 13:06:27
我就是这样修正我的项目的:
我使用Brian贴子中的代码(上面的链接)进行了细微的更改(从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);返回新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;
}
}}
**请注意,全球化视图文件的文件夹arangemnet与Brian的帖子中的层次结构完全相同。
https://stackoverflow.com/questions/21852636
复制相似问题