user1688401
user1688401

Reputation: 1871

Asp.net core Localization always returns english clulture

I am trying to develop a multilanguage project.For static value I used resource(.resx file )

I create two resources file Home.resx(default or English) and home.resx(for the Arabic language) it works for default or English

Then I try to change language

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar");
 var home = Resources.Home.Home1;

But it still return English value instead of Arabic value

here is my startup.cs Configure function

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

   var supportedCultures = new List<System.Globalization.CultureInfo>
            {
                new System.Globalization.CultureInfo("en-US"),

                new System.Globalization.CultureInfo("ar-AR"),

            };
            var options = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            };
            app.UseRequestLocalization(options);
......

what is wrong with my code?

Upvotes: 0

Views: 2902

Answers (1)

pitaridis
pitaridis

Reputation: 2983

Ok, I will tell you what I do in my projects. Type the following code after services.AddMvc() in your ConfigureServices method of the Startup.cs.

IList<CultureInfo> supportedCultures = new List<CultureInfo>
{
    new CultureInfo("en-US"),
    new CultureInfo("fr-FR"),
    new CultureInfo("el-GR"),
};

var MyOptions = new RequestLocalizationOptions()
{
    DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
};
MyOptions.RequestCultureProviders = new[]
{
     new RouteDataRequestCultureProvider() { RouteDataStringKey = "lang", Options = MyOptions }
};

services.AddSingleton(MyOptions);

Now define the following class in your project

public class LocalizationPipeline
{
    public void Configure(IApplicationBuilder app, RequestLocalizationOptions options)
    {
        app.UseRequestLocalization(options);
    }
}

Change your default routing:

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

In use the MiddlewareFilter for each of your controllers.

[MiddlewareFilter(typeof(LocalizationPipeline))]
public class HomeController : Controller
{
    public string GetCulture()
    {
        return $"CurrentCulture:{CultureInfo.CurrentCulture.Name}, CurrentUICulture:{CultureInfo.CurrentUICulture.Name}";
    }
}

You can change the current language like this:

<ul>
    <li>@Html.ActionLink("EN", ViewContext.RouteData.Values["action"] as string, ViewContext.RouteData.Values["controller"] as string, new { lang = "en-US" })</li>
    <li>@Html.ActionLink("FR", ViewContext.RouteData.Values["action"] as string, ViewContext.RouteData.Values["controller"] as string, new { lang = "fr-FR" })</li>
    <li>@Html.ActionLink("GR", ViewContext.RouteData.Values["action"] as string, ViewContext.RouteData.Values["controller"] as string, new { lang = "el-GR" })</li>
</ul>

If you want to support Razor Pages as well, make the following changes. Add the following change the servcies.AddMvc().

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddFolderRouteModelConvention("/", model =>
        {
            foreach (var selector in model.Selectors)
            {
                var attributeRouteModel = selector.AttributeRouteModel;
                attributeRouteModel.Template = AttributeRouteModel.CombineTemplates("{lang=el-GR}", attributeRouteModel.Template);
            }
        });
    });

Use the following MiddlewareFilter attribute over your PageModels

[MiddlewareFilter(typeof(LocalizationPipeline))]
public class ContactModel : PageModel
{
    public string Message { get; set; }

    public void OnGet()
    {
        Message = "Your contact page.";
    }
}

The only thing that I have not managed to do is to automatically define the LocalizationPipeline for all the controllers and PageModels by adding the MiddlewareFilter programmatically inside the Startup.cs.

Upvotes: 2

Related Questions