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!
Routing is responsible for matching incoming HTTP requests and dispatching those requests to the app's executable endpoints. Endpoints are the app's units of executable request-handling code. Endpoints are defined in the app and configured when the app starts.
Localization, on the other hand, is the process of customization to make our application behave as per the current culture and locale. These two things go together. To do globalization we need to use Resource Files.
Use the Localize control to reserve a location on a Web page in which to display localized text. Controls that are outside the body element are ignored. The Localize control inherits from the Literal control and is identical to it in every way.
Localization is the process of adapting software to meet the requirements of local markets and different languages. You can change the messages that are displayed in the Telerik UI for ASP.NET MVC helpers by including an additional script file in the document.
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?}");
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With