更改 ASP.NET Core Razor 页面中的默认登录页面?
Changing the default landing page in ASP.NET Core Razor page?
我试过:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Index", "old");
options.Conventions.AddPageRoute("/NewIndex", "");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
抛出异常:
AmbiguousMatchException: The request matched multiple endpoints.
Matches:
Page: /Index
Page: /NewIndex
我发现 ,建议重命名索引页面,但显然,如果没有给出充分的理由,这也是一种解决方法。我不能只更改默认页面而不重命名 /Index 页面吗?
编辑
建议的 SO 线程没有涵盖我解释的问题,即覆盖默认路由而不必重命名默认 Index
页面。
接受的答案解决了问题。
Razor 页面中的默认页面是那些为其生成了空字符串路由模板的页面。您可以使用自定义 PageRouteModelConvention
删除为 Index.cshtml 页面生成的空字符串路由模板,并将其添加到您想要的任何页面默认页面:
public class HomePageRouteModelConvention : IPageRouteModelConvention
{
public void Apply(PageRouteModel model)
{
if(model.RelativePath == "/Pages/Index.cshtml")
{
var currentHomePage = model.Selectors.Single(s => s.AttributeRouteModel.Template == string.Empty);
model.Selectors.Remove(currentHomePage);
}
if (model.RelativePath == "/Pages/NewIndex.cshtml")
{
model.Selectors.Add(new SelectorModel()
{
AttributeRouteModel = new AttributeRouteModel
{
Template = string.Empty
}
});
}
}
}
您在 ConfigureServices 中注册约定:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.Add(new HomePageRouteModelConvention());
}).SetCompatibilityVersion(CompatibilityVersion.Latest);
您可以在此处阅读有关自定义页面路由模型约定的更多信息:https://www.learnrazorpages.com/advanced/custom-route-conventions
我试过:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Index", "old");
options.Conventions.AddPageRoute("/NewIndex", "");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
抛出异常:
AmbiguousMatchException: The request matched multiple endpoints. Matches:
Page: /Index
Page: /NewIndex
我发现
编辑
建议的 SO 线程没有涵盖我解释的问题,即覆盖默认路由而不必重命名默认 Index
页面。
接受的答案解决了问题。
Razor 页面中的默认页面是那些为其生成了空字符串路由模板的页面。您可以使用自定义 PageRouteModelConvention
删除为 Index.cshtml 页面生成的空字符串路由模板,并将其添加到您想要的任何页面默认页面:
public class HomePageRouteModelConvention : IPageRouteModelConvention
{
public void Apply(PageRouteModel model)
{
if(model.RelativePath == "/Pages/Index.cshtml")
{
var currentHomePage = model.Selectors.Single(s => s.AttributeRouteModel.Template == string.Empty);
model.Selectors.Remove(currentHomePage);
}
if (model.RelativePath == "/Pages/NewIndex.cshtml")
{
model.Selectors.Add(new SelectorModel()
{
AttributeRouteModel = new AttributeRouteModel
{
Template = string.Empty
}
});
}
}
}
您在 ConfigureServices 中注册约定:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.Add(new HomePageRouteModelConvention());
}).SetCompatibilityVersion(CompatibilityVersion.Latest);
您可以在此处阅读有关自定义页面路由模型约定的更多信息:https://www.learnrazorpages.com/advanced/custom-route-conventions