简体   繁体   English

ASP.NET Core 中的翻译问题,通过 ASP.NET _Layout.cshtml 中的核心本地化

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

I am trying to learn programming in ASP.NET Core by making simple programs, but I got stuck with translating some parts of texts by using a localization feature.我正在尝试通过制作简单的程序来学习 ASP.NET Core 中的编程,但我在使用本地化功能翻译部分文本时遇到了困难。 For example, I created Resources and folders with all needed resource files with translated words and phrases.例如,我创建了资源和文件夹,其中包含所有需要的资源文件以及翻译的单词和短语。 For _Layout.cshtml i created Resources -> Views -> Shared -> _Layout.en.resx and _Layout.fr.resx对于 _Layout.cshtml,我创建了 Resources -> Views -> Shared -> _Layout.en.resx 和 _Layout.fr.resx

I tried to use this type of code but it doesn't work, the page is loading but when I change the culture from en to fr the words in _Layout don't change, only what I get is the words write in @localizer quotes in both languages.我尝试使用这种类型的代码,但它不起作用,页面正在加载,但是当我将文化从 en 更改为 fr 时,_Layout 中的单词不会改变,只有我得到的是@localizer 引号中写的单词两种语言。

The code in _Layout is the same as yours. _Layout 中的代码与您的相同。

The differences in Startup.cs: Startup.cs 的区别:

In ConfigureServices:在配置服务中:

services.AddLocalization(opt => { opt.ResourcesPath = "Resources"; }); services.AddLocalization(opt => { opt.ResourcesPath = "资源"; }); services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization(); 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;
            });

In Configure i add only that code: app.UseRequestLocalization(app.ApplicationServices.GetRequiredService<IOptions>().Value);在配置中,我只添加该代码: app.UseRequestLocalization(app.ApplicationServices.GetRequiredService<IOptions>().Value);

I made this to work this file _Culture.cshtml (problem with adding code)我做了这个来工作这个文件_Culture.cshtml(添加代码的问题)

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

And I got side like this:我得到了这样的一面:

https://i.stack.imgur.com/1vRWE.jpg And after changing the language (in this example i have polish language but normally it is french) https://i.stack.imgur.com/Fbn8j.jpg https://i.stack.imgur.com/1vRWE.jpg更改语言后(在这个例子中我有波兰语,但通常是法语) https://i.stack.imgur.com/Fbn8j.jpg

Here is a whole working demo:这是一个完整的工作演示:

1.Add resource file in Resources/Views/Shared folder in root project: 1.在根项目的Resources/Views/Shared文件夹中添加资源文件:

在此处输入图像描述

2.Edit your resource file( _Layout.fr.resx ) like below: 2.编辑您的资源文件( _Layout.fr.resx ),如下所示:

Note :Be sure you have added the correct value for key( Home , Privacy , Book List .Book List contains space ).注意:确保您为键添加了正确的值( HomePrivacyBook List 。图书列表包含空格)。

在此处输入图像描述

3.Create _Culture.cshtml : _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 your _Layout.cshtml like below: 4.更改您的_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 sure add AddViewLocalization in your Startup.cs like below: 5.确保在 Startup.cs 中添加AddViewLocalization ,如下所示:

Note: It should be: app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>() not app.ApplicationServices.GetRequiredService<IOptions>() .注意:它应该是: 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: 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);
}

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM