在ASP.NET Core中,全球化和本地化可以通過以下方式來實現:
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("zh-CN")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在Views文件夾中創建對應的資源文件,用于存放各種語言的本地化字符串。如在Resources文件夾中創建對應的資源文件:Home.en-US.resx和Home.zh-CN.resx。
在Controller中使用IStringLocalizer來獲取本地化字符串:
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
}
public IActionResult Index()
{
ViewData["Message"] = _localizer["Hello World!"];
return View();
}
通過以上方式,在ASP.NET Core中實現全球化和本地化功能。當用戶訪問網站時,根據其瀏覽器的語言偏好設置,系統會自動選擇對應的本地化字符串進行顯示。