0
votes

I am trying to localize my ASP.NET Core application. I want to localize the Views using a ViewLocalizer and @Localizer["Teststring"]. In my Startup.cs i do:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddLocalization();

        services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();

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

            options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");

            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
        });


    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

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

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

I added a possibility to set the language which uses this method in my controller:

    [HttpPost]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );

        return LocalRedirect(returnUrl);
    }

My resource file for the german version of the Home/Index for example is named Views.Home.Index.de.resx. Sadly the selection of a language doesn't change the strings and I can't figure out what I'm doing wrong. The setlanguage method is called correctly.

1
where is your resx file located? Have you set the ResourcesPath property? - Kahbazi
It is located in the Rescources folder. I have also tried to replace services.AddLocalization(); with services.AddLocalization(options => options.ResourcesPath = "Resources"); - TomBombadil

1 Answers

0
votes

Found the problem. I was missing the localization.aspnetcore.taghelpers package. There was no error message telling me that and no tutorial