Dave Mateer
Dave Mateer

Reputation: 17956

Require route value in Razor Pages for folder

In ASP.NET Core Razor Pages, how do I set up routing for a folder to require a particular route id to be present? Here is my folder structure:

[Pages]
 - Index.cshtml
 - GeneralPage.cshtml
 - [Company]
    - Billing.cshtml
    - Manage.cshtml
    - Users.cshtml

Any page within the "Company" folder should have a route parameter (integer {companyId}) before the page name. The following should all be valid requests:

The following should fail:

AddFolderRouteModelConvention sounds promising, but its use is not obvious to me.

Any suggestions on the most straightforward way to achieve the routing above?

Upvotes: 3

Views: 317

Answers (1)

Dave Mateer
Dave Mateer

Reputation: 17956

This is not a general solution, but works for the simple layout above:

options.Conventions.AddFolderRouteModelConvention("/Company", model =>
{
    Regex templatePattern = new Regex("^Company/");
    foreach (var selector in model.Selectors)
    {
        selector.AttributeRouteModel.Template =
            templatePattern.Replace(selector.AttributeRouteModel.Template, "Company/{companyId}/");
    }
});

Upvotes: 3

Related Questions