ASP.NET MVC5使用路由

时间:2017-03-16 09:36:07

标签: asp.net-mvc asp.net-mvc-5 currentculture uiculture

我是使用MVC5的新手,我尝试使用不同语言的网站。 到目前为止,我做了一些配置,当我点击不同的语言时,它会更改网址但不会更改视图中的文本。 如果有人有想法,这是我的代码:

在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}") }
);

在filterConfig中:

filters.Add(new CultureFilter(defaultCulture: "en"));

在_Layout View Page:

@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>

同样在View Page:

@using Test.App_LocalResources;
@{
    ViewBag.Title = GlobalRes.Title;
}

我将语言文件放在App_LocalResources中,名称为Global.resx和Global.ru.resx。

所以Title,Money和DateTime总是得到英文文本,而不是俄罗斯文本。 我错过了什么吗?

0 个答案:

没有答案