I've been messing around with ASP.NET Core 2.0 since its release, and in particular the new Razor Pages feature which seems like WebForms done right. I'm not totally convinced that Razor Pages is a good idea for my apps (UPDATE: I have been convinced), but for now it's been quite interesting to learn.

There was, however, one particular thing that bugged me while I was trying to set up a sample project for a forthcoming post: how in the heck do you change the landing page for the app? It took a bit of digging, but I eventually did come up with the answer to that question, and in fact you can do it in just one line of code.

App Structure

Razor Pages works off a folder structure, so by default all pages are in the /Pages folder:

A screenshot of a default Razor Pages project, showing the root Pages folder and all pages under it

But in my sample project, I wanted to have a deeper folder structure, and I wanted the default page of the app to be a page within another folder. In my particular case, I created the directory /Pages/Employees, and I wanted the /Pages/Employees/Index.cshtml page to be the default page for the entire application.

A screenshot of my sample project, showing the new /Pages/Employees folder and its pages, with the Index page highlighted

Routing the URLs

In short, I wanted the following URLs to all map to the /Pages/Employees/Index.cshtml page:

http://localhost:50857/employees/index
http://localhost:50857/employees/
http://localhost:50857/

Supporting the first two URLs was easy; in fact, that's what Razor Pages is designed to do by default. But getting the third url to map to the appropriate page involves changing a setting in the Startup.cs file.

When we include MVC as a service into our app, we can optionally use another method called AddRazorPagesOptions() like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddRazorPagesOptions(options =>
    {
        //...
    });
}

Within that AddRazorPagesOptions() method, we can set things like route conventions and the root directory for pages. It turns out that, to set a default route for a page, you execute this call:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/Employees/Index", "");
    });
}

Note the parameters for the AddPageRoute() method. The first parameter takes the path to the page for which we want to add a route. The second identifies the route that should map to the page. In my case, since I wanted the default page for the entire app to be the /Pages/Employees/Index.cshtml page, I pass in an empty string. And, voila, the page now maps correctly:

A screenshot of a browser, showing that the URL http://localhost:50857 now shows the /Pages/Employees/Index page

Here's hoping this helps someone else who's learning about Razor Pages!

Happy Coding!