Home > database >  Is there a way in a Razor Pages app to change the default starting route to an Area?
Is there a way in a Razor Pages app to change the default starting route to an Area?

Time:12-30

When you create an ASP.Net Core Web App with Individual Accounts it adds an Identity Area along with the regular Pages folder. Since I don't want to be working between the Pages folder along with the Area folder, I want to create a Home Area that my app's default route "/" will route to. I was able to accomplish this for the Index page by adding this to Program.cs:

builder.Services.AddRazorPages(options =>
{
    options.Conventions.AddAreaPageRoute("Home", "/Index", "");
});

Obviously, this just takes care of the single Index page, but if I wanted to have an About or Privacy page, I would have to add AreaPageRoutes for them as well. I tried a couple different things with AddAreaFolderRouteModelConvention that I am too embarrassed to show here, but was ultimately unable to find out how to make it work.

Is it possible and secondly, is it bad practice, to map the default routing of Pages to a specific Area?

CodePudding user response:

You can use a PageRouteModelConvention to change the attribute route for pages in an area:

public class CustomPageRouteModelConvention : IPageRouteModelConvention
{
    public void Apply(PageRouteModel model)
    {
        foreach (var selector in model.Selectors.ToList())
        {
            selector.AttributeRouteModel.Template = selector.AttributeRouteModel.Template.Replace("Home/", "");
        }
    }
}

Generally, my advice regarding areas in Razor Page applications is don't use them. They add additional complexity for no real gain at all. You have already found yourself fighting against the framework as soon as you introduced your own area. QED.

The only place areas serve a real purpose is within Razor class libraries, so you have to live with an area when using the Identity UI. But you don't have to use the Identity UI. You can take code inspiration from it and implement your own version in your existing Pages folder.

  • Related