我尝试在 Blazor 应用程序中实现本地化,但在尝试通过视图中的键获取资源值时遇到一些问题。
我怎样才能做到这一点?
到目前为止,这是我的代码:
启动.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>
页面位置
Project
-- Pages
- - 帐户
------ 登录.razor
资源文件位置
Project
- 资源
---- 页面
- - - 帐户
-------- 登录.bg-BG.resx
这对我有用:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
...
}
索引剃刀
@page "/"
@using System.Globalization
<h1>Localization test</h1>
Localized field: @(localizer["Field1"])
@code {
[Inject] public Microsoft.Extensions.Localization.IStringLocalizer<Index> localizer { get; set; }
}
My resx
文件的存储方式如下:
Resources\Pages\Index.resx
Resources\Pages\Index.cs.resx
...
然后,根据 UICulture,调用时返回正确的本地化字符串localizer["Field1"]
.
在代码中,我这样更改 UICulture:
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("cs-CZ");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)