要在ASP.NET MVC .NET Core 3.1中实现语言切换,您可以遵循以下步骤:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("zh-CN")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
在Views文件夹中创建Resources文件夹,并在其中添加与视图对应的资源文件。例如,如果您有一个名为Index.cshtml的视图,则创建一个名为Index.en-US.resx和Index.zh-CN.resx的资源文件。
在视图中使用@using和@inject指令引用资源文件。例如,在Index.cshtml视图中,您可以添加以下代码:
@using Microsoft.Extensions.Localization
@inject IStringLocalizer localizer
@localizer["Welcome"]
public IActionResult Index(string culture)
{
if (!string.IsNullOrEmpty(culture))
{
CultureInfo.CurrentCulture = new CultureInfo(culture);
CultureInfo.CurrentUICulture = new CultureInfo(culture);
}
return View();
}
现在,当您访问带有区域设置参数的URL时,视图将根据相应的资源文件显示本地化字符串。