如何在同一个项目中同时拥有 MVC 和 Razor 页面?

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

我有一个带有 Razor 页面的 ASP.NET 核心应用程序,我想在其中利用 MVC,因此我将 Controllers 文件夹添加到其中,并添加了 Views 以及 services.AddMvc() 启动和另一个端点它,然后尝试 运行 如果它有效。只是我 运行 项目,我想测试它是否 return 简单视图,我在默认地址后添加控制器名称和操作,但它显示 "This localhost page can找不到.

你能帮我配置我的应用程序吗?

如果要将 MVC 添加到 Razor Page 项目:

1.You需要在ConfigureServices中添加services.AddControllers();并在startup.cs中配置mvc路由:

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?}");
    });
}

2.You 需要添加一个名为 Controllers 的文件夹和一个名为 Views.

的文件夹

然后将包含 _Layout.cshtml_ValidationScriptsPartial.cshtmlPages/Shared 文件夹复制到 Views 文件夹。

并将Pages/_ViewImports.cshtml复制到Views/_ViewImports.cshtmlPages/_ViewStarts.cshtml复制到Views/_ViewStarts.cshtml

这是一个项目结构: