Search code examples
asp.net-mvcroutesrazor-pagesvisual-studio-2022.net-7.0

.net 7 Razor pages with multiple route conventions not working


I got an old .net4.8 web app that uses MVC and controllers and trying to convert(Rewrite) it to .net 7 razor pages.

I am trying to change the old url routing to be a standard.

My Razor page routeing works fine and is as follows.

@page "/flights/{FromIata:length(3)?}/{ToIata:length(3)?}"

i have also tried

@page "/flights/{FromIata?}/{ToIata?}"

in my program.cs I added the other route conventions.

builder.Services.AddRazorPages()
                .AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AddPageRoute("/Flights", "/flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights", "/flights/{FromIata:length(3)}-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights", "/flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights", "/flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
                    options.Conventions.AddPageRoute("/Flights", "/flights/to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights", "/flights/to-{ToIata:length(3)}-{CityName}");
                    options.Conventions.AddPageRoute("/Flights", "/flights/{*url}");
                })

if I browse to the page with the standard convection it works fine but if i use any of the other conventions I get a 404 error.

What I am trying to do is either load the page with the other convention. i.e /Flights/to-kul-kuala%20lumpur or if i use that conventions it does a permanent redirect to the new url format. i.e Flights/kul

Any suggestions would be greatly appreciated.

Thanks in advance.


Solution

  • the solutions was as above to remove the /

    @page "flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
    

    and add index to the convention.

    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/{FromIata:length(3)}-{ToIata:length(3)}");
    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/to-{ToIata:length(3)}");
    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/flights/to-{ToIata:length(3)}-{CityName}");
    options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/flights/{*url}");