Search code examples
c#asp.netasp.net-mvcvisual-studiorazor

How to map URL to follow folder scheme in ASP.NET Razor


I have this folder layout:

Pages
|
|- index.cshtml
|- products.cshtml
|- products
           |
           |- product1.cshtml
           |- product2.cshtml
|- settings.cshtml

The root folders work perfectly (index.cshtml, products.cshtml, settings.cshtml) and the URL maps respectivley, for example products.cshtml will map to https://example.com/products

I'd like the .cshtml files in the products subfolder of the Pages folder to map like this too. For example, product1.cshtml maps to the URL https://example.com/products/product1 etc.

Currently in each product file I have @page "/products/product1" which I do not know if it is the correct way, it seems to half work but has weird behaviour if there is a trailing / on the end of the URL, CSS isnt loaded etc.


Solution

  • You can achieve this with a custom Page route action convention.

    The example code is as follows:

     services.AddRazorPages(options =>
                    {
                        options.Conventions.AddPageRoute("/products/product1", " product1");
                        options.Conventions.AddPageRoute("/products/ product2", " product2");
                        options.Conventions.AddFolderRouteModelConvention("/", model =>
                        {
                            var selectorCount = model.Selectors.Count;
                            for (var i = selectorCount - 1; i >= 0; i--)
                            {
                                var selectorTemplate = model.Selectors[i].AttributeRouteModel.Template;
     
                                if (selectorTemplate.StartsWith("products")) 
                                    model.Selectors.RemoveAt(i);
                            }
                        });
                    });