剃刀页面中的路线数据

时间:2020-03-29 13:44:26

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

剃须刀页面支持MVC吗?

endpoints.MapControllerRoute(
                    name: "prefix",
                    pattern: "{prefix}/{controller=Home}/{action=Index}/{id?}");

我需要在页面url前面加一个前缀:

/prefix/Index

/prefix/Privacy 

我可以访问路线数据,只是不知道如何将其映射到剃须刀页面

1 个答案:

答案 0 :(得分:1)

要在剃须刀页面中实现它,首先创建一个继承自IPageRouteModelConvention

的类
public class CustomRouteModelConvention : IPageRouteModelConvention
{
    public void Apply(PageRouteModel model)
    {
        List<SelectorModel> selectorModels = new List<SelectorModel>();
        foreach (var selector in model.Selectors.ToList())
        {
            var template = selector.AttributeRouteModel.Template;
            selectorModels.Add(new SelectorModel()
            {
                AttributeRouteModel = new AttributeRouteModel
                {
                    Template = "/prefix" + "/" + template
                }
            });
        }
        foreach (var m in selectorModels)
        {
            model.Selectors.Add(m);
        }
    }
}

然后,在startup.cs ConfigureServices方法中,添加以下代码:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages().AddRazorPagesOptions(opts =>
        {
            opts.Conventions.Add(new CustomRouteModelConvention());
        });
     }

这是指here

更新

要动态制作“前缀”,可以将“前缀”更改为{0}以替换您输入的任何字符串。

public class CustomRouteModelConvention : IPageRouteModelConvention
{
    public void Apply(PageRouteModel model)
    {
        List<SelectorModel> selectorModels = new List<SelectorModel>();
        foreach (var selector in model.Selectors.ToList())
        {
            var template = selector.AttributeRouteModel.Template;
            selectorModels.Add(new SelectorModel()
            {
                AttributeRouteModel = new AttributeRouteModel
                {
                    Template = "/{0}" + "/" + template
                }
            });
        }
        foreach (var m in selectorModels)
        {
            model.Selectors.Add(m);
        }
    }
}

结果是:

enter image description here