如何在.NET Core中本地化路由操作/控制器

时间:2019-07-02 08:51:01

标签: url .net-core localization internationalization

已进行搜索,但找不到与本地化控制器/操作有关的任何问题,而不仅仅是将区域性本身添加到了URL。

我通过在URL中插入/ es /来实现本地化的.NET Core网站(在controller / action是其设置方式(即www.bla.com/es/account/profile)之前)。

这使用区域性设置并将区域性保存在cookie中,并且站点使用IStringLocalizer,并且一切正常。

我的问题是,我现在需要翻译路线本身。

www.bla.com/account/profile

OR

www.bla.com/es/cuenta/perfil

(仅以Google翻译为例)

我不认为我现在担心翻译任何查询字符串或变量名,只担心操作名和控制器名本身。

1 个答案:

答案 0 :(得分:0)

要添加中间件来重写url,请根据当前使用的内容,将其添加到Startup.ConfigureUseRoutingUseRoute之前的UseMvc方法中。

//This definition should be moved as a field or property.
//And the value should be loaded dynamically.
var urlMappings = new Dictionary<string, string>
{
    { "/es/cuenta/perfil", "/account/profile" },
    // others
};

//Rewriting the matched urls.
app.Use(next => http =>
{
    if (urlMappings.TryGetValue(http.Request.Path.Value, out var result))
    {
        http.Request.Path = new PathString(result);
    }
    return next(http);
});

这只是有关如何实现它的示例,尽管url映射规则应在服务内进行管理。