我是使用 MVC5 的新手,我尝试用不同的语言做一个网站。到目前为止,我做了一些配置,当我单击另一种语言时,它会更改 url,但不会更改视图中的文本。如果有人知道,这是我的代码:
在 App_Data 文件夹中,我有 2 个文件: CultureConstraint 和 CultureFilter
public class CultureFilter : IAuthorizationFilter
{
private readonly string defaultCulture;
public CultureFilter(string defaultCulture)
{
this.defaultCulture = defaultCulture;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var values = filterContext.RouteData.Values;
string culture = (string)values["culture"] ?? this.defaultCulture;
CultureInfo ci = new CultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
public class CultureConstraint : IRouteConstraint
{
private readonly string defaultCulture;
private readonly string pattern;
public CultureConstraint(string defaultCulture, string pattern)
{
this.defaultCulture = defaultCulture;
this.pattern = pattern;
}
public bool Match(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.UrlGeneration &&
this.defaultCulture.Equals(values[parameterName]))
{
return false;
}
else
{
return Regex.IsMatch((string)values[parameterName], "^" + pattern + "$");
}
}
}
在 RouteConfig 我添加:
routes.MapRoute(
name: "DefaultWithCulture",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { culture = new CultureConstraint(defaultCulture: "en", pattern: "[a-z]{2}") }
);
在过滤器配置中:
filters.Add(new CultureFilter(defaultCulture: "en"));
在 _Layout 视图页面中:
@using Test.App_LocalResources;
@{
var routeValues = this.ViewContext.RouteData.Values;
var controller = routeValues["controller"] as string;
var action = routeValues["action"] as string;
}
<ul>
<li>@Html.ActionLink("Russia", @action, @controller, new { culture = "ru" }, new { rel = "alternate", hreflang = "ru" })</li>
<li>@Html.ActionLink("English", @action, @controller, new { culture = "en" }, new { rel = "alternate", hreflang = "en" })</li>
</ul>
<div style="background: silver">
@GlobalRes.Money: <br />
@GlobalRes.DateAndTime: <br />
</div>
并且还在查看页面中:
@using Test.App_LocalResources;
@{
ViewBag.Title = GlobalRes.Title;
}
我将语言文件放在 App_LocalResources 中,名称为 Global.resx 和 Global.ru.resx。
所以 Title、Money 和 DateTime 总是得到英文文本,而不是俄罗斯文本。我错过了什么吗?