首页 > 解决方案 > 如何在 .NET Core 中本地化路由操作/控制器

问题描述

搜索但找不到任何关于本地化控制器/操作的问题,而不仅仅是将文化本身添加到 URL。

我有一个本地化的 .NET Core 网站,通过将 /es/ 插入 URL(在控制器/操作之前是它的设置方式,即 www.bla.com/es/account/profile)。

这使用文化设置并将文化保存在 cookie 中,并且该站点使用 IStringLocalizer 并且一切正常。

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

www.bla.com/account/profile

或者

www.bla.com/es/cuenta/perfil

(谷歌翻译只是例子)

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

标签: url.net-corelocalizationinternationalization

解决方案


要添加中间件来重写 url,请将其添加到您的Startup.Configure方法之前UseRouting,,UseRouteUseMvc取决于当前使用的内容:

//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 映射规则应该在服务中管理。


推荐阅读