13

By default a Razor Page app goes to Home/Index

Is there a way to change this to Home/App?

This is quite easy in MVC, but Razor pages using a different routing setup and thus MVC routing does not apply.

I would think it would be in options somewhere, but I don't see it:

services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
                options. ??SetDefaultPage??
            });

I have tried this:

options.Conventions.AddPageRoute("/App", "");

But now two default routes are found and an error is generated:

AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

Page: /App

Page: /Index

It's possible to resolve this error by removing Pages/Index.cshtml from the project, but I wanted to keep that page as well.

Community
  • 1
  • 1
Greg Gum
  • 33,478
  • 39
  • 162
  • 233

4 Answers4

5

Pretty sure it isn't possible. The docs say the runtime controls the search for Index as the default. I couldn't find where that happens in the current release, but IndexFileName is a static in the new internal PageRouteModelFactory class added to the upcoming release:

private static readonly string IndexFileName = "Index" + RazorViewEngine.ViewExtension;

It doesn't seem like it would be difficult to just add a config property to RazorPagesOptions, though. The ASP.NET guys are pretty responsive, I'd open a request as a GitHub issue and hope for the best.

McGuireV10
  • 9,572
  • 5
  • 48
  • 64
5

In my case the ambiguity was caused by Pages/Index.cshtml left in project. This worked:

  1. options.Conventions.AddPageRoute("/App", "");
  2. remove or rename Pages/Index.cshtml
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
EgurnovD
  • 165
  • 1
  • 4
1

I solved the issue by using Microsoft.AspNetCore.Rewrite:

Then adding code to replace the default Index action, in my case with Portfolio:

var options = new RewriteOptions()
    .AddRedirect("^", "portfolio"); // Replace default index page with portfolio

More detailed article about rewrite options - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?tabs=aspnetcore2x

Gavin
  • 5,629
  • 7
  • 44
  • 86
1

Another way is to simply redirect from the Index OnGet method, like so:

    public class IndexModel : PageModel
    {
        public IActionResult OnGet()
        {
            return Redirect("/Welcome");
        }
    }

Notice that I have change the return type of the OnGet method.

Michael
  • 397
  • 2
  • 10