Search code examples
c#asp.net-mvcasp.net-coreasp.net-core-mvcrazor-pages

How can have Both MVC and Razor page in the same Project?


I have an ASP.NET Core application with Razor pages and I want take advantages of MVC into it.

I added

  • Controllers folder to it with Views
  • and also services.AddMvc() to startup
  • and another endpoint to it.

I did run the project and tested if

  • the simple view is returned
  • and if the added controller and action after the default address works

But it did not work and returned

"This localhost page can’t be found".

Would you please help me how I config my app?


Solution

  • If you want to add MVC to a Razor Page project:

    Add services to startup.cs

    First you need to add services.AddControllers(); to ConfigureServices and configure mvc routing in startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddControllers();
        ...
    }
    
    // This method gets called by the runtime. 
    // Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    Add folders

    Second you need to add two folders with these names

    • Controllers
    • Views.

    Then copy

    • Pages/Shared folder which contains _Layout.cshtml
    • and _ValidationScriptsPartial.cshtml

    to Views folder.

    And copy

    • Pages/_ViewImports.cshtml to Views/_ViewImports.cshtml,
    • Pages/_ViewStarts.cshtml to Views/_ViewStarts.cshtml.

    Here is a project structure:

    MVC and Razor folder structure