Program.cs
中的代码:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("zh-CN")
};
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture(supportedCultures.FirstOrDefault());
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
var localizationOptions = app.Services.GetService<IOptions<RequestLocalizationOptions>>()?.Value;
localizationOptions.FallBackToParentCultures = true;
localizationOptions.FallBackToParentUICultures = true;
app.UseRequestLocalization(localizationOptions);
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
API控制器中的代码:
public class TestController : ControllerBase
{
private readonly IStringLocalizer<ResourcesController> _localizer;
public TestController(IStringLocalizer<ResourcesController> localizer)
{
_localizer = localizer;
}
[HttpGet("TestCulture")]
public async Task<IActionResult> TestCulture()
{
var testMsg = _localizer["NotFound"].Value;
return Ok(testMsg);
}
}
我基本上尝试了教程,甚至尝试了chatGPT,但它不起作用。关于如何解决这个问题有什么建议吗?非常感谢!