如何实现本地化ASP网CORE MVC

时间:2018-05-30 11:49:05

标签: c# localization asp.net-core-mvc

我无法想象如何在ASP.NET Core MVC网站上使用本地化: 我关注this网站,但我想我忘记了一些事情:

初创公司:

 public void ConfigureServices(IServiceCollection services)
        {
        services.AddMvc(
                config =>
                {
                    config.Filters.Add<ActionFilter>();
                })
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization();

        services.Configure<RequestLocalizationOptions>(option =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr"),
                };
                option.DefaultRequestCulture = new RequestCulture(culture: "fr", uiCulture: "fr");
                option.SupportedCultures = supportedCultures;
                option.SupportedUICultures = supportedCultures;
            });
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
        var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(locOptions.Value);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

HomeController:

    public class HomeController : Controller
    {

    private readonly IStringLocalizer<HomeController> _localizer;

            public HomeController(IStringLocalizer<HomeController> localizer)
                {
                    _localizer = localizer;
                }
    public IActionResult Index()
            {
                return View()
            }
}

Index.cshtml

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

@{
    ViewData["Title"] = Localizer["Home"];
}

<h1>News</h1>
<h2>@Localizer["Home"]</h2>

我有Resources Folder文件HomeController.fr.resx,其中Home =&gt;确定了Accueil关系。

函数Request.HttpContext.Features.Get<IRequestCultureFeature>().RequestCulture.Culture.Name返回fr,但页面始终显示Home而不是Accueil

我错过了本地化的事情吗?

1 个答案:

答案 0 :(得分:1)

我终于想清楚为什么它不起作用,我只是忘了添加Localization.AspNetCore.TagHelpers NugetPackage。