ASPNET Core 和本地化与 resx 文件

ASPNET Core and localization with resx files

我无法加载我的资源文件,或者其他原因使我的应用程序无法加载正确的值。

这是我的 Startup.cs:

services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
services.AddMvc()
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, 
         opts => { opts.ResourcesPath = "Resources"; })                    
        .AddDataAnnotationsLocalization();

services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
    {
        new CultureInfo("da-DK")
    };

    options.DefaultRequestCulture = new RequestCulture(culture: "da-DK", 
    uiCulture: "da-DK");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

这是我的控制器:

public class CustomerController : Controller
{
    private readonly IHtmlLocalizer<CustomerController> _localizer;

    public CustomerController(IHtmlLocalizer<CustomerController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult MyAccount()
    {
        string test = Language.MyAccount;
        ViewData["Message"] = _localizer["MyAccount"];

        return View();
    }

我的资源文件位于应用程序根目录中名为 Resources 的文件夹中,名称为:

_localizer["MyAccount"]; 请问return一个字符串"MyAccount"好象没找到汉化的东西。

Language.MyAccount; will return "My account" 这是默认值。 没有人会找到我对这把钥匙的丹麦语翻译。

谁能看出我做错了什么?

现在我想通了,部分得益于 Daniel J. G. 是的,我需要

app.UseRequestLocalization(new RequestLocalizationOptions(...))

在我的 Startup.cs 的配置部分。

但是让 _localizer 真正找到资源文件的是更改 resx.designer 文件的命名空间。

代替

namespace AO.Customer.Resources

应该是

namespace AO.Customer

命名空间的资源部分是由它自己的服务添加的。

谢谢丹尼尔

要使用 _localizer["MyAccount"],您必须将资源文件命名为 IHtmlLocalizer< 此处 >[=21 中指定的类型=].

Language.da-DK.resx , Language.resx 必须命名为 CustomerController.da-DK.resx, CustomerController.en.resx

查看.net core 本地化的官方文档here