ASP.NET 核心翻译问题 ASP.NET _Layout.cshtml 核心本地化

Problem with translation in ASP.NET Core via ASP.NET Core localization in _Layout.cshtml

我正在尝试通过制作简单的程序来学习 ASP.NET Core 中的编程,但是我无法通过使用本地化功能来翻译文本的某些部分。 例如,我创建了资源和文件夹,其中包含所有需要的资源文件以及翻译的单词和短语。对于 _Layout.cshtml,我创建了资源 -> 视图 -> 共享 -> _Layout.en.resx 和 _Layout.fr.resx

我尝试使用这种类型的代码,但它不起作用,页面正在加载,但是当我将区域性从 en 更改为 fr 时,_Layout 中的文字没有改变,只有我得到的是文字用两种语言写在@localizer 引号中。

_Layout中的代码和你的一样

Startup.cs的区别:

在配置服务中:

services.AddLocalization(opt => { opt.ResourcesPath = "资源"; }); services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();

        services.Configure<RequestLocalizationOptions>(
            opt =>
            {
                var supportCulteres = new List<CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr")
                };
                opt.DefaultRequestCulture = new RequestCulture("en");
                opt.SupportedCultures = supportCulteres;
                opt.SupportedUICultures = supportCulteres;
            });

在配置中我只添加了代码: app.UseRequestLocalization(app.ApplicationServices.GetRequiredService().Value);

我做了这个来处理这个文件_Culture.cshtml(添加代码的问题)

https://i.stack.imgur.com/WV9pn.jpg

我得到这样的一面:

https://i.stack.imgur.com/1vRWE.jpg 在更改语言后(在这个例子中我有波兰语,但通常是法语) https://i.stack.imgur.com/Fbn8j.jpg

这是一个完整的工作演示:

1.Add 根项目 Resources/Views/Shared 文件夹中的资源文件:

2.Edit 你的资源文件(_Layout.fr.resx)如下:

注意:确保您为键添加了正确的值(HomePrivacyBook List。图书列表包含 space).

3.Create _Culture.cshtml:

@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var culture = Context.Features.Get<IRequestCultureFeature>();
    var cultureList = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<div>
    <form asp-controller="Home" asp-action="CultureManagement"
          asp-route-returnUrl="@returnUrl" method="post">
        <select name="culture" asp-for="@culture.RequestCulture.UICulture.Name" asp-items="cultureList"
                onchange="this.form.submit();" >
        </select>
    </form>
</div>

4.Change 你的 _Layout.cshtml 如下所示:

@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer localizer

<!DOCTYPE html>
<html lang="en">
<head>
    //...
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MvcCore3_1</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">@localizer["Home"]</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">@localizer["Privacy"]</a>
                        </li>
                    </ul>

                    //add the partial here
                    @await Html.PartialAsync("_Culture")
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2020 - MvcCore3_1 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

5.Be 确保在您的 Startup.cs 中添加 AddViewLocalization,如下所示:

注:应该是:app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>()不是app.ApplicationServices.GetRequiredService<IOptions>().

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

        services.Configure<RequestLocalizationOptions>(
         opt =>
         {
             var supportCulteres = new List<CultureInfo>
             {
                new CultureInfo("en"),
                new CultureInfo("fr")
             };
             opt.DefaultRequestCulture = new RequestCulture("en");
             opt.SupportedCultures = supportCulteres;
             opt.SupportedUICultures = supportCulteres;
         });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        var options = app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);
        
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {               
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}"); 
        });

    }

6.Controller:

[HttpPost]
public IActionResult CultureManagement(string culture, string returnUrl)
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return LocalRedirect(returnUrl);
}

结果: