Search code examples
asp.net-corerazor-pagesasp.net-routing

.net 8 Razor Pages routing without default route to @page directive


I have an .net 8 razor page application where i've added page routes from database with the following code:

options.Conventions.AddPageRoute(route.FullName, route.Key.ToString());

For example i've added the page route /A64592D0-05AD-4E0D-8A0C-5E5259800A19 for the page /Account/Login. Now I want to avoid that someone can access the page directly with /Account/Login.

Background: Each page can be accessed by more then one route in our navigation tree, this way it's possible to evaluate on which position the user is currently on the tree and handle different permissions based on the position and user.

I just could set the @page directive to some unused value, but that wouldn't avoid the possibility to access the page with that value.

How can i remove or disable the default page route for all pages?


Solution

  • You can use a PageRouteModelConvention to clear all the default routes. An example would look like this:

    public class CustomPageRouteModelConvention : IPageRouteModelConvention
    {
        public void Apply(PageRouteModel model)
        {
            model.Selectors.Clear();
        }
    }
    

    Then you register it in Program.cs, ensuring you make your AddPageRoute calls afterwards:

    builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
    {
        options.Conventions.Add(new CustomPageRouteModelConvention());
        options.Conventions.AddPageRoute("/Account/Login", "A64592D0-05AD-4E0D-8A0C-5E5259800A19");
    });
    

    Or depending on your logic, you could add the custom routes within the custom PageRouteModelConvention. The Apply method is called for every page in your app once at startup.