0

Hi I am trying to implement the Localization for ASP.NET Core but I cannot return the translated value - it always return the "key" value - "Load". When I print the culture - it returns "fr", so the culture is set correctly. Honestly I am out of ideas...

I am following this tutorial: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization

Looking at this sample too: https://github.com/aspnet/Entropy/tree/dev/samples/Localization.StarterWeb

When I build the project the Resource file is compiled and is copied at: obj/Debug/netcoreapp1.1/BoilerPlate.Resources.Controllers.ValuesController.fr.resources

and

bin/Debug/netcoreapp1.1/fr/BoilerPlate.resources.dll

$ dotnet --info
.NET Command Line Tools (1.0.0-rc3-004530)

Product Information:
 Version:            1.0.0-rc3-004530
 Commit SHA-1 hash:  0de3338607

Startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddLocalization(options => options.ResourcesPath = "Resources");

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

           // State what the default culture for your application is. This will be used if no specific culture
           // can be determined for a given request.
           options.DefaultRequestCulture = new RequestCulture(culture: "fr", uiCulture: "fr");

           // You must explicitly state which cultures your application supports.
           // These are the cultures the app supports for formatting numbers, dates, etc.
           options.SupportedCultures = supportedCultures;

           // These are the cultures the app supports for UI strings, i.e. we have localized resources for.
           options.SupportedUICultures = supportedCultures;
       });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseStatusCodePages();
        app.UseDeveloperExceptionPage();

        var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(locOptions.Value);

        app.UseMvc();
    }

ValuesController.cs

private readonly IStringLocalizer<ValuesController> _localizer;
        public ValuesController(IStringLocalizer<ValuesController> localizer)
        {
            _localizer = localizer;
        }

 // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {

            var rqf = Request.HttpContext.Features.Get<IRequestCultureFeature>();
            var culture = rqf.RequestCulture.Culture;
            System.Console.WriteLine($"Culture: {culture}");

            return _localizer["Load"];
            // return "value";
        }

Resources/Controllers.ValuesController.fr.resx

...
  <data name="Load" xml:space="preserve">
    <value>Load this value!</value>
  </data>
...

1 Answer 1

1

I believe that the problem is with your folder structure related to resources. You should store the resources in this structure:

Resources > Controllers > YourController.fr.resx

Resources > Views > YourController > YourView.fr.resx

Also, I missed the services.AddMvc().AddViewLocalization(); on startup to localize views.

Edit

I just did a test with a new project. Here is the Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseRequestLocalization(BuildLocalizationOptions());

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc();
    }

    private RequestLocalizationOptions BuildLocalizationOptions()
    {
        var supportedCultures = new List<CultureInfo>
        {
            new CultureInfo("fr")
        };

        var options = new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("fr"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        };

        // this will force the culture to be fr. 
        // It must be changed to allow multiple cultures, but you can use to test now
        options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
        {
            var result = new ProviderCultureResult("fr", "fr");

            return Task.FromResult(result);
        }));

        return options;
    }

Hope this helps you.

Regards,

Sign up to request clarification or add additional context in comments.

4 Comments

Hi @Tiago I tried both structures. According to the documentation, we can use this structure: Resource name Dot or path naming Resources/Controllers.HomeController.fr.resx Dot Resources/Controllers/HomeController.fr.resx Path and I am not using Views. I just return response from the controller. This is WebAPI - no Views are used.
@PetarIvanov, I updated my answer based on a new project I just created. It worked well. I just would like to add that I tested using the folder structure of my answer.
Strange thing ... I created a new project on Windows, copy/pasted my code and it worked. Send the newly created project to the *nix machine, run it, and it worked. Since then my old code started working too. The only difference is the reference to that VS2017 is adding to the csproj file: <ItemGroup> <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="Resources\Controllers\ValuesController.fr.resx"> <Generator>ResXFileCodeGenerator</Generator> </EmbeddedResou...
I am wondering whether this issue has been solved, cause I suspect this is my problem also. stackoverflow.com/questions/54914990/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.