Search code examples
asp.net-mvcasp.net-coreasp.net-core-mvcasp.net-core-localization

ASPNET Core and localization with resx files


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?


Solution

  • 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