Search code examples
asp.net-corerazor-pages

Add Route Parameter to all Razor Pages in an Area


I'm trying to add a route parameter to all pages in a Razor Pages Area so every URL within an Area has an OrgId e.g. /dashboard/{orgId}/{page}/{route}. I can add them using the AddAreaPageRoute as shown below, but I can't help feeling there's a way to apply this to all pages without having to define an entry for every page in the Area. Is there a way to create a route for all pages in an Area?

.AddRazorPages(options =>
{
    options.Conventions.AddAreaPageRoute("Dashboard", "/Index", "Dashboard/{orgId}");
    options.Conventions.AddAreaPageRoute("Dashboard", "/AddItem", "Dashboard/{orgId}/AddItem");
    options.Conventions.AddAreaPageRoute("Dashboard", "/Items", "Dashboard/{orgId}/Items");
    options.Conventions.AddAreaPageRoute("Dashboard", "/Items/Index", "Dashboard/{orgId}/Items/{id}");
})

Solution

  • You can change your code like below:

    services.AddRazorPages(options =>
            {
                options.Conventions.AddAreaFolderRouteModelConvention("Dashboard", "/", model =>
                {
                    foreach (var selector in model.Selectors)
                    {
                        var c = selector.AttributeRouteModel.Template.ToString();
                        selector.AttributeRouteModel = new AttributeRouteModel
                        {
                            Order = -1,
                            Template =c.Replace("Dashboard", "Dashboard/{orgId}")
    
                        };
                    }
                });
             });
    

    You can see the details in the doc.