Search code examples
c#asp.net-core.net-coreasp.net-core-mvcrazor-pages

How to change ASP.NET Core area name in routing?


In my project, I have an area called Admin. By default, the route to its pages is, for example, /admin/reports/add.

I want to change the URL for that area, so instead of /admin/reports/add, the URL will be /secret/reports/add. I don't want to change the folder name, just the URL (PS: I am using ASP.NET Core Razor pages).

I tried app.MapAreaControllerRoute(), RazorPagesOptions, etc.

Here is my Program.cs file:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

And this is the folder structure:

enter image description here


Solution

  • Thank you all for your answers. This one worked for me.

    public class AdminToSecretPageRouteModelConvention : IPageRouteModelConvention
    {
        public void Apply(PageRouteModel model)
        {
            foreach (var selector in model.Selectors.Select(x => x.AttributeRouteModel))
            {
                if (selector?.Template is null)
                {
                    continue;
                }
                
                selector.Template = selector.Template.Replace("Admin", "Secret");
            }
        }
    }