簡體   English   中英

在 asp.net 內核中使用 .resx 文件

[英]Using .resx files in asp.net core

我目前正試圖圍繞如何使網站以多種語言提供,但我真的不知道從哪里開始。 我已經閱讀了 microsoft 的文檔 -->

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-5.0

我也關注了這個 stackoverflow 線程,目前正在第 5 步 -->

如何獲取asp.net內核中的.resx文件字符串

我目前制作了一個名為“Layout.nl.resx”的.resx 文件,它應該可以識別 Layout.cshtml 的名稱。 我也在我的 startup.cs 中做了這個來本地化路徑並配置我將使用的文化信息。

using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Localization;

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                new CultureInfo("nl-NL"),
                new CultureInfo("en-US"),
                new CultureInfo("dk-DK"),
                new CultureInfo("de-DE")
                };
                options.DefaultRequestCulture = new RequestCulture("nl-NL", "nl-NL");
                //Formatting Numers, Dates, etc.
                options.SupportedCultures = supportedCultures;
                //UI strings that we have localized
                options.SupportedUICultures = supportedCultures;

            });
            services.AddMvc()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<JagerUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            var supporterCultures = new[] { "nl-NL", "en-US", "dk-DK", "de-DE" };
            var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supporterCultures[0])
                .AddSupportedCultures(supporterCultures)
                .AddSupportedUICultures(supporterCultures);

            app.UseRequestLocalization(localizationOptions);
            Console.WriteLine("The current Culture Language is: " + CultureInfo.CurrentCulture + "The Thread CultureInfo is: " + Thread.CurrentThread.CurrentCulture);
            
        }

現在我的目標是將 Layout.cshtml 中的 Headers 值從 'Products' 和 'My Orders' 更改為 'Producten' 和 'Mijn Orders',這些值已在位於 Layout.nl.resx 文件中描述文件夾“資源”。

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

            Console.WriteLine("The new CultureInfo is now: " + CultureInfo.CurrentCulture);
            //this will display on the console: The new CultureInfo is now: en-US
            return LocalRedirect(returnUrl);
        }
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options


@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = 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 title="@Localizer["Request culture provider:"] @requestCulture?.Provider.GetType().Name">
    <form id="selectLangue" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> 
        <select name="culture" onchange="this.form.submit();" asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
        </select>
    </form>

</div>

我的問題是:如何從 .resx 文件中訪問這些信息,我必須在哪里初始化 IStringLocalizer<> 並更改 Layout.cshtml 中的值

更新

我添加了一個下拉列表,它現在創建一個 cookie 並將 CultureInfo 設置為可以在上面的代碼字段中看到的所選語言。 我當前的問題是訪問或能夠使用我制作的資源文件。 它被稱為“Views.Home.Index.nl-NL.resx”。 因為它必須與文件夾名稱中的視圖名稱相匹配(我認為)。

好的,經過大量閱讀和詢問后,我找到了如何使用資源文件的答案。 我已經完成了大部分設置。 您在services.Configure()中定義文化類型,使用serivices.AddLocalization()定義希望在哪個路徑中找到資源,並使用services.AddMvc().AddViewLocalization()指定視圖格式。

然后在public void Configure()方法下,您將定義您將要查找的支持的語言類型。 又名 Index.en-US.resc。 您正在使用app.UseRequestLocalization()添加 RequestLocalizationMiddleware,它將根據您的客戶提供給您的信息設置文化。

現在..重要的部分是了解如何訪問資源文件是了解如何設置尋路。 資源文件命名中,他們談論路徑Resources/View/Home/Index.fr.resc在您的 Resources 文件夾中,您將不得不 map 一個結構,就像您的普通視圖放置在層次結構中一樣 Views -> into Home -> into the索引.cshtml 文件。

設置完成后,您可以使您的內容可本地化,這可以在使應用程序的內容可本地化查看文檔的本地化下找到:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-5.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM