在ASP.NET Core 7.0中启用本地化需要进行以下步骤:
1.在Startup.cs文件中添加以下代码:
using Microsoft.AspNetCore.Localization;
using System.Globalization;
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("es-ES"),
new CultureInfo("zh-CN"),
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("es-ES"),
new CultureInfo("zh-CN"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
}
2.在Controllers文件夹中创建一个控制器,并使用IStringLocalizer
作为依赖注入。
例如,我们可以创建一个名为HomeController的控制器如下:
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Localized.Models;
namespace Localized.Controllers
{
public class HomeController : Controller
{
private readonly IStringLocalizer _localizer;
public HomeController(IStringLocalizer localizer)
{
_localizer = localizer;
}
public IActionResult Index()
{
ViewData["HelloMessage"] = _localizer["HelloMessage"];
return View();
}
}
}
3.在Resources文件夹中创建一个名为Shared.resx的文件,并添加资源,例如:
键:HelloMessage
值(英文版):Hello, World!
值(西班牙文版):`¡Hola