对于本地化,我更喜欢包含语言的前 2 个字母的直接、清晰且可读的链接(例如:mysite.com/en/mypage),这样可以使用所需的语言获得正确的链接。
我发现与 Blazor Server 完美配合而无需 Cookie 的唯一解决方案是使用 “Pier-Luc Bonneville” 创建的包 “BlazorServerUrlRequestCultureProvider”;它使用起来毫不费力,而且效果极佳。
用法:
安装包BlazorServerUrlRequestCultureProvider(与.Net 5.0完美配合):
Install-Package BlazorServerUrlRequestCultureProvider -Version 1.0.0
Startup.cs:
using BlazorServerUrlRequestCultureProvider;
// ...
//------------------------------
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ...
// Set the Resources folder name:
services.AddLocalization(options => options.ResourcesPath = "Resources");
// ...
}
}
//------------------------------
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
#region Localization
var supportedCultures = new[]
{
new CultureInfo("en"),
new CultureInfo("ar"),
};
var options = new RequestLocalizationOptions
{
// Select a default language:
DefaultRequestCulture = new RequestCulture("en"),
// For Numbers, Dates, etc:
SupportedCultures = supportedCultures,
// For strings that we have localized in .resx files:
SupportedUICultures = supportedCultures
};
app.UseUrlRequestLocalization(options);
#endregion
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
app.UseRequestLocalization();
}
这就是你所需要的!没有 Cookie 和控制器!
现在像往常一样使用 StringLocalizer(在我的例子中,资源文件名是 Resource 文件夹中的 App.resx 和 App.ar.resx):
MyPage.razor:
@page "/ar/MyPage"
@page "/en/MyPage"
@inject IStringLocalizer<App> localizer
<h1>@localizer["My Translated Text Here !"]</h1>
感谢和感谢“Pier-Luc Bonneville”的出色工作。 Project Website , NuGet .
--
奖励:
为了让您的生活更轻松,请使用工具 ResXManager 轻松管理和翻译资源文件,它是一款免费且出色的工具,可为您节省大量时间。