Search code examples
asp.net-corerazor-pagesasp.net-core-8

How to add .html to razor pages url?


I'm new to ASP.NET and Razor Pages. I've a web app where I want to show URLs with html extension. So, the localhost/login.html should go to Pages/Login.cshtml. I've read about AddRazorPages and AddRazorPagesOptions() but all I can understand that by default Razor Pages routes localhost/ to Pages/index.cshtml and localhost/product/create to Pages/Product/Create.cshtml and so on. How to intercept this is beyond me and whatever I read is getting way above my head.

I've tried this with no luck:

(Program.cs)
builder.Services.AddRazorPages().AddRazorPagesOptions(opt =>
{
    opt.Conventions.AddPageRoute("/*.html", "/*");
});

Can anyone help me (with little explanation) how to achieve this? Or point me to resources. Thanks!


Solution

  • IPageRouteModelConvention Interface Allows customization of the PageRouteModel.

    PageConventionCollection.AddFolderRouteModelConvention Method creates and adds an IPageRouteModelConvention that invokes an action on PageRouteModel instances for all page under the specified folder.

    So if we want to show URLs with html extension, we need to custom the PageRouteModel , try the below code:

    builder.Services.AddRazorPages().AddRazorPagesOptions(o =>
      {
          o.Conventions.AddFolderRouteModelConvention("/", pageRouteModel =>
          {
              foreach (var selectorModel in pageRouteModel.Selectors)
                  selectorModel.AttributeRouteModel.Template =  selectorModel.AttributeRouteModel.Template + ".html";
          });
     });
    

    result: the localhost/Privacy.html should go to Pages/Privacy.cshtml:

    enter image description here

    Or add @page "/Privacy.html" in the Pages/Privacy.cshtml ,but this way we need to add it for every cshtml page.