语言资源在 .NET Core API 中不起作用

问题描述 投票:0回答:1

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();

文件夹结构:\

  1. 我的项目(API)
  2. ├── 控制器
  3. │ ├── TestController.cs
  4. ├── 资源
  5. │ ├── 共享
  6. │ --├── SharedResource.cs
  7. │ --├── SharedResources.en-US.resx
  8. │ --└── SharedResources.zh-CN.resx

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,但它不起作用。关于如何解决这个问题有什么建议吗?非常感谢!

asp.net-core .net-core asp.net-core-webapi
1个回答
0
投票

这是一个项目结构问题。经过我的测试,请遵循这个结构。同时,请检查您的文件名是否正确。

MyProject (API)
├── Controllers
│ ├── TestController.cs
│
├── Resources
│ ├── SharedResources.en-US.resx
│ ├── SharedResources.zh-CN.resx
├── SharedResources.cs

enter image description here enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.