I am developing an online store using ASP.NET Core 2 and I am struggling with how to implement route localization, ex. depending from the country where user is from I want him to see /en/products or /pl/produkty.
I managed to implement culture as part of the url, like /en/...., and user can also change default language by clicking a button on the website. However, I have no idea how to localize whole urls. I don't want to put hundreds of urls in Startup.cs (MapRoute). I need a better solution, which is working automatically behind the scenes.
If someone change directly the url (ex. en/products) and put pl instead of en, I want him/her to be redirected to pl/produkty automatically.
I hope you can help me!
here's a very good ressource here:
Asp.Net core Localization deep dive
Precisely here's what you're looking for:
IList<CultureInfo> supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("fi-FI"),
};
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
var requestProvider = new RouteDataRequestCultureProvider();
localizationOptions.RequestCultureProviders.Insert(0, requestProvider);
app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture=en-US}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(localizationOptions);
subApp.UseMvc(mvcRoutes =>
{
mvcRoutes.MapRoute(
name: "default",
template: "{culture=en-US}/{controller=Home}/{action=Index}/{id?}");
});
});
});