meta info

MVC/Razor Pages and XML Based Localization Setup

By Ziya Mollamahmut

There are multiple ways to configure routing for localization in MVC projects, and you may get routing errors if the routing setup is not configured correctly.

Option 1 - Routing Setup Using Model Convention

  • Configure MvcOptions by inserting model convention in startup, this will add {culture} route segment automatically to all routes in the application.
services.AddMvc()
    .AddMvcOptions(ops => ops.Conventions.Insert(0, new RouteTemplateModelConventionMvc()))
    .AddXLocalizer<...>(...);
  • Define a route for each action
public class HomeController : Controller
{
    [Route("")]
    public IActionResult Index() { ... }

    [Route("privacy")]
    public IActionResult Privacy() { ... }

    [Route("error")]
    public IActionResult Error() { ... }
}

Option 2 - Routing Setup Using Route Pattern

Just add {culture=en} to te route pattern:

app.MapControllerRoute(
   name: "default",
   pattern: "{culture=en}/{controller=Home}/{action=Index}/{id?}");

Thank to @Julian for his comment