代码之家  ›  专栏  ›  技术社区  ›  Asons Oliver Joseph Ash

本地化页面名称ASP.NET核心2.1

  •  3
  • Asons Oliver Joseph Ash  · 技术社区  · 7 年前

    创建Razor页面时,例如“事件.cshtml,将其模型名设置为

    @page
    @model EventsModel
    

    在本例中,页面的名称是“Events”,URL如下所示

    http://example.com/Events
    

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

    有了这个,我也可以使用这样的网址,仍然服务于“事件”页面

    http://example.com/hvaskjer
    

    我计划支持更多的语言和好奇,这是建议的方式来设置本地化的网页名称/路线的?,还是有更合适的, 实现同样目标的方法。

    我的意思是,有了上面的例子,有10种语言的15页,使用起来很混乱 options.Conventions.AddPageRoute("/Page", "/side"); 150次。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Mike Brind    7 年前

    你可以用 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页面为应用程序构建路由。这个 Apply 方法对框架找到的每个可导航页面执行。如果当前页的相对路径与数据中的相对路径匹配,则会为每个选项添加一个附加模板。

    你把新的公约登记在 ConfigureServices

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