Search code examples
asp.net-corerazorrazor-pages

Why is app.UseMvc() added when creating a Razor Pages Project?


I'm new to ASP.NET Core and Razor Pages. After doing some research, I elected to use Razor Pages over MVC as I thought there would be more benefits and liked the idea of the code-behind page models etc. I chose ASP.NET Core Web Application -> Web Application and created a new project targeting ASP.NET Core 2.2.

The default template appears to create a "pure" Razor Pages project, e.g. the Pages folder instead of MVC's Controller/Models/Views.

I'm getting really confused, however, because there are still elements of MVC in the Razor Pages project: app.useMvc() in Startup.cs, the inclusion of _ViewStart.cshtml, the use of ViewData["x"], etc.

Realistically, this is fine and one can press on, but then following the Razor Pages guides and supposed conventions seems to go haywire; _PageStart.cshtml doesn't actually work from my testing.

Where am I going wrong?


Solution

  • Razor Pages, whilst they do not use controllers, are actually part of the MVC Framework and require you to call app.UseMvc() in order to initilise everything it needs, including routing, etc.

    You can also use UseMvc to do some configuration to your application:

     app.AddMvc()
        .AddRazorPagesOptions(options =>
            {
                options.Conventions.Add("options");
            });
    

    More information on this can be found at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/razor-pages-conventions?view=aspnetcore-2.2