my web app gets translation from the french resource, idk why

234 Views Asked by At

I started some weeks ago to develop a web application using asp.net core 3.0, now I got to the phase where I must develop the localization service, to simplify my code, I will only write the new "parts" so here they are: startup.cs: the ConfigureServices method:

 services.AddLocalization(options => options.ResourcesPath = "Resources");
                services.AddMvc(option => option.EnableEndpointRouting = false)
                   .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                   .AddDataAnnotationsLocalization()
                   .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                services.Configure<RequestLocalizationOptions>(options =>
                {
                    var supportedCultures = new List<CultureInfo>
                        {
                            new CultureInfo("fr-FR"),
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                        };
    
                    options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en-US");
                    options.SupportedCultures = supportedCultures;
                    options.SupportedUICultures = supportedCultures;
                });
                services.AddTransient<SharedResources>();

the SharedResources.cs is located in the app root the Configure method

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

_ViewImports.cshtml:

@using Microsoft.Extensions.Localization
@inject IStringLocalizer<Backoffice.SharedResources> LangDefault
@addTagHelper *, Localisation

a View:

@using Microsoft.AspNetCore.Mvc.Localization
@model some-model
@inject IViewLocalizer Localizer
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
    <ul class="navbar-nav flex-grow-1">
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-page="/Index">@Localizer["Sede"]</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">@Localizer["FirstName"]</a>
        </li>
    </ul>
</div>

my app only gets the french translation from Views.[SomeController].[SomeAction].fr.resx, I couldn't find how to make a select list to change the language, what I find are either for API apps or an old .net core, I found this guide that helped me, but it missed some points, can you provide an adapted guide or some help? thanks

1

There are 1 best solutions below

6
On BEST ANSWER

Here is a demo worked:

/Shared/Partial:

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@*@{
        ViewData["Title"] = "Partial";
    }

    <h1>Partial</h1>*@

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Home"
          asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> 
        <select name="culture"
                                                                                                               onchange="this.form.submit();"
                                                                                                               asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
        </select>
    </form>
</div>

_layout.cshtml:

@using Microsoft.AspNetCore.Mvc.Localization

@inject IViewLocalizer Localizer
 <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
        <div>
            @Localizer["Hello"]
        </div>
        <div class="col-sm-6 text-right">
            @await Html.PartialAsync("Partial")
        </div>
    </div>

Startup.cs:

ConfigureServices:

services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
            .AddViewLocalization(
                LanguageViewLocationExpanderFormat.Suffix,
                opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization();

            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en-US"),
                        new CultureInfo("fr-FR"),
                        new CultureInfo("de-DE")
                    };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;

            });

Configure:

app.UseHttpsRedirection();
            var supportedCultures = new[] { "en-US", "fr-FR", "de-DE" };
            var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
                .AddSupportedCultures(supportedCultures)
                .AddSupportedUICultures(supportedCultures);

            app.UseRequestLocalization(localizationOptions);

            app.UseStaticFiles();

HomeController:

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

Resources:

enter image description here

result: enter image description here