Search code examples
c#asp.net-corerazor-pagesasp.net-core-5.0

Rename Pages/Shared directory in ASP.NET Core Razor Pages


I'm using ASP.NET Core 5 Razor Pages. The common templates go in Pages/Shared, but I need to rename it to Pages/Foo.

How do I instruct the runtime to look for files in Pages/Foo?

I think it's possible in Startup.ConfigureServices():

services.AddRazorPages(options => {
  options.Conventions.???      // what goes here?
});

Solution

  • The paths used to locate Razor Pages views are defined in PageViewLocationFormats, which is a property of RazorViewEngineOptions. You can manipulate this collection to customise these paths.

    Here's an example:

    services.AddRazorPages()
        .AddRazorOptions(o =>
        {
            var indexOfPagesShared = o.PageViewLocationFormats.IndexOf("/Pages/Shared/{0}.cshtml");
    
            o.PageViewLocationFormats.RemoveAt(indexOfPagesShared);
            o.PageViewLocationFormats.Insert(indexOfPagesShared, "/Pages/Foo/{0}.cshtml");
        });
    

    There's a tonne of different approaches to modifying the list, but this example shows how to replace the existing /Pages/Shared path with /Pages/Foo. It makes assumptions about the root (/Pages) and the file-extension, but these are typical.

    Note that if you're using areas, there's also an AreaPageViewLocationFormats property.