ASPNET核心和resx文件本地化

时间:2017-03-19 13:33:28

标签: asp.net-mvc asp.net-core asp.net-core-mvc asp.net-core-localization

我无法加载我的资源文件,或者其他一些事情是让我的应用程序加载正确的值。

这是来自我的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的文件夹中,名为:

  • Language.da-DK.resx
  • Language.resx

_localizer [“MyAccount”]; 将返回一个字符串“MyAccount”,好像它在本地化中没有找到任何内容。

Language.MyAccount;将返回“我的帐户”,这是默认值。 没有人会发现我对此密钥的丹麦语翻译。

谁能看到我做错了什么?

2 个答案:

答案 0 :(得分:1)

现在我想出来了,部分得到了Daniel J. G.的帮助 是的,我需要

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

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

但是让_localizer实际找到资源文件的事情是改变了resx.designer文件的命名空间。

代替

namespace AO.Customer.Resources

应该是

namespace AO.Customer

命名空间的Resources部分由服务自己添加。

谢谢Daniel

答案 1 :(得分:0)

对于使用_localizer [“MyAccount”],您必须将资源文件命名为 IHtmlLocalizer&lt;中指定的类型。 此处&gt;

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

查看.net核心本地化here

的官方文档