ASPNET Core and localization with resx files

一曲冷凌霜 提交于 2019-12-24 06:40:42

问题


I cant get my resource files loaded, or some thing else is keeping my app to load correct values.

This is from my 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;
});

And this is from my Controller:

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

My resource files are located in a folder named Resources in the root of my app, and are called:

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

The _localizer["MyAccount"]; Will return a string "MyAccount" as if it did not find anything in the localization.

The Language.MyAccount; will return "My account" which is the default value. No one will find my danish translation of this key.

Can anyone see what i am doing wrong?


回答1:


Now i figured it out, partly helped by Daniel J. G. Yes, i needed to have the

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

in the Configure part of my Startup.cs.

But the thing that made the _localizer actually find the resource file, was changing the namespace of the resx.designer file.

in stead of

namespace AO.Customer.Resources

it should be

namespace AO.Customer

The Resources part of the namespace was added by the service it self.

Thanks Daniel




回答2:


For using _localizer["MyAccount"] you have to have the resource files named as the type specified in IHtmlLocalizer< here > .

Language.da-DK.resx , Language.resx have to be named CustomerController.da-DK.resx, CustomerController.en.resx

Take a look over the official documentation for .net core localization here



来源:https://stackoverflow.com/questions/42887204/aspnet-core-and-localization-with-resx-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!