ASP.NET Core 2.1 的本地化页面名称

Localized page names with ASP.NET Core 2.1

创建 Razor 页面时,例如"Events.cshtml",一个将其型号名称设置为

@page
@model EventsModel

在这种情况下页面的名称是 "Events",URL 看起来像

http://example.com/Events

为了能够使用挪威语的页面名称,我将以下内容添加到 "Startup.cs"

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddRazorPagesOptions(options => {
        options.Conventions.AddPageRoute("/Events", "/hvaskjer");
        options.Conventions.AddPageRoute("/Companies", "/bedrifter");
        options.Conventions.AddPageRoute("/Contact", "/kontakt");
});

有了这个我也可以像这样使用 URL 并且仍然服务于 "Events" 页面

http://example.com/hvaskjer

我计划支持更多语言,想知道这是设置本地化页面名称“s/route”的推荐方法吗?还是有更合适的 正确方法 完成相同的方法。

我的意思是,对于上面的示例,有 15 个页面,10 种语言,使用 options.Conventions.AddPageRoute("/Page", "/side"); 150 次 gets/feels 很乱。

您可以使用 IPageRouteModelConvention 界面执行此操作。它提供对 PageRouteModel 的访问,您可以在其中有效地添加更多路由模板以匹配特定页面。

这是基于以下服务和模型的非常简单的概念证明:

public interface ILocalizationService
{
    List<LocalRoute> LocalRoutes();
}
public class LocalizationService : ILocalizationService
{
    public List<LocalRoute> LocalRoutes()
    {
        var routes = new List<LocalRoute>
        {
            new LocalRoute{Page = "/Pages/Contact.cshtml", Versions = new List<string>{"kontakt", "contacto", "contatto" } }
        };
        return routes;
    }
}

public class LocalRoute
{
    public string Page { get; set; }
    public List<string> Versions { get; set; }
}

它所做的只是为特定页面提供选项列表。 IPageRouteModelConvention 实现如下所示:

public class LocalizedPageRouteModelConvention : IPageRouteModelConvention
{
    private ILocalizationService _localizationService;

    public LocalizedPageRouteModelConvention(ILocalizationService localizationService)
    {
        _localizationService = localizationService;
    }

    public void Apply(PageRouteModel model)
    {
        var route = _localizationService.LocalRoutes().FirstOrDefault(p => p.Page == model.RelativePath);
        if (route != null)
        {
            foreach (var option in route.Versions)
            {
                model.Selectors.Add(new SelectorModel()
                {
                    AttributeRouteModel = new AttributeRouteModel
                    {
                        Template = option
                    }
                });
            }
        }
    }
}

在启动时,Razor Pages 会为应用程序构建路由。 Apply 方法针对框架找到的每个可导航页面执行。如果当前页面的相对路径与您的数据中的相对路径匹配,则会为每个选项添加一个额外的模板。

您在 ConfigureServices 中注册了新约定:

services.AddMvc().AddRazorPagesOptions(options =>
{
    options.Conventions.Add(new LocalizedPageRouteModelConvention(new LocalizationService()));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);