gpt4 book ai didi

asp.net-core - Blazor 本地化

转载 作者:行者123 更新时间:2023-12-01 18:30:19 24 4
gpt4 key购买 nike

我尝试在 Blazor 应用程序中实现本地化,但在尝试通过 View 中的键获取资源值时遇到一些问题。

我怎样才能实现这个目标?

这是迄今为止我的代码:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });

services.Configure<RequestLocalizationOptions>(
options =>
{
List<CultureInfo> supportedCultures =
new List<CultureInfo>
{
new CultureInfo("bg-BG"),
new CultureInfo("en-US")
};

options.DefaultRequestCulture = new RequestCulture("bg-BG");

// Formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;

// UI string
options.SupportedUICultures = supportedCultures;

});

services.AddRazorPages();

services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });

services.AddApplicationRepositoryServices();

services.AddSingleton<WeatherForecastService>();
}

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

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");

// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseAuthentication();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();

endpoints.MapBlazorHub();

endpoints.MapFallbackToPage("/_Host");
});
}
<小时/>

登录.razor

@page "/login"

@using Microsoft.Extensions.Localization

@inject IStringLocalizer<Login> Localizer

<button type="submit" class="btn btn-primary w-100">@Localizer["LoginButtonText"]</button>
<小时/>

页面位置

项目

-- 页面

---- 帐号

------登录.razor

<小时/>

资源文件位置

项目

-- 资源

---- 页面

------帐户

--------登录.bg-BG.resx

最佳答案

这对我有用:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
...
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
...
}

索引.razor

@page "/"
@using System.Globalization

<h1>Localization test</h1>

Localized field: @(localizer["Field1"])

@code {
[Inject] public Microsoft.Extensions.Localization.IStringLocalizer<Index> localizer { get; set; }
}

我的 resx 文件存储如下:

Resources\Pages\Index.resx
Resources\Pages\Index.cs.resx
...

enter image description here

然后,根据 UICulture,在调用 localizer["Field1"] 时返回正确的本地化字符串。

在代码中,我这样更改 UICulture:

CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("cs-CZ");

关于asp.net-core - Blazor 本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59050522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com