剃须刀页面支持MVC吗?
endpoints.MapControllerRoute(
name: "prefix",
pattern: "{prefix}/{controller=Home}/{action=Index}/{id?}");
我需要在页面url前面加一个前缀:
/prefix/Index
/prefix/Privacy
我可以访问路线数据,只是不知道如何将其映射到剃须刀页面
答案 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);
}
}
}
结果是: