Route localization in ASP.NET Core 2

纵饮孤独 提交于 2019-12-04 16:29:45

问题


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!


回答1:


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?}");
        });
    });
});


来源:https://stackoverflow.com/questions/47079689/route-localization-in-asp-net-core-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!