【问题标题】:ASP.NET Core Razor Page multiple path routingASP.NET Core Razor Page 多路径路由
【发布时间】:2018-07-20 12:27:00
【问题描述】:

我正在使用 ASP.NET Core 2.0 Razor 页面(不是 MVC)构建一个系统,但在为页面添加多个路由时遇到问题。例如,所有页面都应该能够通过 abc.com/language/segment/shop/mypage 或 abc.com/language/shop/mypage 访问,其中两条路径都指向同一个页面。段路径部分是可选的,然后页面使用可选的段信息进行处理。

CombineTemplates 标记中的问号语法似乎不起作用,它似乎只在路径的最后一部分起作用。浏览到 {segment?} 部分中没有值的 url 会导致 404。例如:

AttributeRouteModel.CombineTemplates("{language}/{segment?}/shop", selector.AttributeRouteModel.Template);

我尝试了下面这样的代码,但它只是将两个路径相互附加,我需要能够将它们都启用为有效。

options.Conventions.Add(new DefaultPageRouteModelConvention());
options.Conventions.Add(new SegmentPageRouteModelConvention());

在 ASP.NET MVC 中,我可以添加两个不同的路由,指向同一个区域/控制器/动作,并使用两个不同的 MapRouteWithName。 任何想法如何使用 .NET Razor Page 语法来做到这一点?

【问题讨论】:

    标签: c# asp.net-core-2.0 razor-pages


    【解决方案1】:

    此代码有效:

    添加一个约定(不是两个不同的约定):

    options.Conventions.Add(new CombinedPageRouteModelConvention());
    

    在新约定中,添加两个路由选择器:

    private class CombinedPageRouteModelConvention : IPageRouteModelConvention
        {
            private const string BaseUrlTemplateWithoutSegment = "{language}/shop";
            private const string BaseUrlTemplateWithSegment = "{language}/{segment}/shop";
            public void Apply(PageRouteModel model)
            {
                var allSelectors = new List<SelectorModel>();
                foreach (var selector in model.Selectors)
                {
                    //setup the route with segment
                    allSelectors.Add(CreateSelector(selector, BaseUrlTemplateWithSegment));
    
                    //setup the route without segment
                    allSelectors.Add(CreateSelector(selector, BaseUrlTemplateWithoutSegment));
                }
    
                //replace the default selectors with new selectors
                model.Selectors.Clear();
                foreach (var selector in allSelectors)
                {
                    model.Selectors.Add(selector);
                }
            }
    
            private static SelectorModel CreateSelector(SelectorModel defaultSelector, string template)
            {
                var fullTemplate = AttributeRouteModel.CombineTemplates(template, defaultSelector.AttributeRouteModel.Template);
                var newSelector = new SelectorModel(defaultSelector)
                {
                    AttributeRouteModel =
                    {
                        Template = fullTemplate
                    }
                };
                return newSelector;
            }
        }
    

    【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2022-07-14
    • 2019-05-22
    • 2019-01-09
    • 2018-03-17
    • 2020-05-06
    • 2021-05-04
    • 1970-01-01
    • 2018-02-17
    相关资源
    最近更新 更多