I could not find a way to specify a page route in a strongly typed manner for the razor pages in .Net Core 6.0.
The @page directive expects a string and would throw an exception for a variable.
The RouteAttribute is simply ignored
There is a way of adding extra routes in Program.cs like this:
builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Index", "default.aspx");
});
But it is still required for you to provide the page name as a parameter.
There is however a way of mapping a PageModel class to the corresponding page name.
You need to implement IPageApplicationModelConvention and add it to the service container:
public class InitStructurePageRouteModelConvention : IPageApplicationModelConvention
{
public void Apply(PageApplicationModel model)
{
var page = Structure.FindByTypeInfo(model.ModelType);
if (page != null)
{
page.PagePath = model.ViewEnginePath;
page.Area = model.AreaName;
}
}
}
The PageApplicationModel has everything we need to do the mapping between PageModel and PagePath.
The "Structure" is a tree like object holding various metadata (including PageModel type, PagePath and Area) about application pages.
The registration in service container:
builder.Services.AddRazorPages(options =>
{
options.Conventions.Add(new InitStructurePageRouteModelConvention());
})
The "Apply" method will be called for every razor page.
So instead of setting the page routes according to the application structure you can have the structure populated with the PageModels and map the Page names during the Apply call of IPageApplicationModelConvention.
Kind of reverse approach: Not setting the routes according to your structure but updating your structure with existing routes (or page names).
The downside is that you cannot have multiple pages for one PageModel class.
But you can now use the page.PagePath from the Structure object in the routing generation.
Sorry for not providing more details about the Structure object but it would make the post too big while being unrelated to your needs.
@attribute
there's no need for@page
. You can also have the constant in your page model (and you might have to add a@using
). And because attribute is already code, you don't need an@
in front of your constant variable. – Penney