Category Archives: Uncategorized

Multilangual MVC application

Create a new ASP.Net MVC application

Add a Resources folder and add two files with this folder:
Views.Home.Index.en.resx
Views.Home.Index.nl.resx

Add an entry WelcomeText to both files. With a dutch value in the nl.resx file and an english value in the en.resx file.

Now update your startup.cs to support multiple languages. Edit your Program.cs in the root of the project file. Add this code right before var app = builder.Build();

// Add services to the container.
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("nl") };
    options.DefaultRequestCulture = new RequestCulture("en");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

And this code right before app.Run();

var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("nl") };
var localizationOptions = new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
};

app.UseRequestLocalization(localizationOptions);

That’s it. Now you can switch between languages by adding ?culture=en or ?culture-nl to your url.

Share