Search code examples
c#.netasp.net-web-apilocalizationhttprequest

Using IStringLocalizer using resources files in WebApi


In a WEB API in .NET 6.0, I'd like access resources based on a language. I do this :

In Startup.cs :

services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllersWithViews()
        .AddViewLocalization
        (LanguageViewLocationExpanderFormat.SubFolder)
        .AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options => {
    var supportedCultures = new[] { "fr-BE", "nl-BE" };
    options.SetDefaultCulture(supportedCultures[0])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);
});

The resource files are in Resources\Controllers\ with 2 files MyController.fr-BE.resx and MyController.nl-BE.resx

In the controller :

private readonly IStringLocalizer<MyController> _localizer;

public MyController(IStringLocalizer<MyController> localizer)
{
    _localizer = localizer;
}

In one of the entry point I do this :

public ActionResult Get()
{
    var article = _localizer["Article"];

    return Ok();
}

The article variable has these values :

Name = "Article"
ResourceNotFound = true
article.SearchedLocation = API.Resources.Controllers.MyController
Value = "Article"

In the resource file, I have for "Article" in MyController.fr-BE : "Article FR" and in MyController.nl-BE : "Article NL"

The request call from postman has in the header :

Accept-Language = fr-BE

Am I missed something ?

Thanks,


Solution

  • In your startup you misconfigured LanguageViewLocaionExpanderFormat to SubFolder. It should be Suffix, see the docs.

    LanguageViewLocaionExpanderFormat has two options:

    1. SubFolder: Locale is a subfolder under which the view exists.
    2. Suffix: Locale is part of the view name as a suffix.

    The sub folder would have a file structure: Resources/controllers/fr-BE/filename.resx Whilst The suffix would have the following structure: Resources/controllers/filename.fr-BE.resx. Where filename should be the name of the controller.

    services.AddControllersWithViews()
            .AddViewLocalization
            (LanguageViewLocationExpanderFormat.SubFolder)
            .AddDataAnnotationsLocalization();
    

    Your resources should look something like this:

    enter image description here