我有一个带有 Razor 页面的 ASP.NET Core 应用程序,我想在其中利用 MVC,所以我将 Controllers 文件夹添加到其中,并添加了 Views 和 services.AddMvc()
以启动和它的另一个端点,然后尝试运行(如果它有效)。我简单地运行该项目,我想测试它是否返回简单 View ,并在默认地址后添加 Controller 名称和操作,但它显示“找不到此本地主机页面”。
你能帮我配置我的应用吗?
最佳答案
如果要将 MVC 添加到 Razor Page 项目:
1.需要在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.您需要添加一个名为Controllers
的文件夹和一个名为Views
的文件夹。
然后将包含_Layout.cshtml
和_ValidationScriptsPartial.cshtml
的Pages/Shared
文件夹复制到Views
文件夹。
并将Pages/_ViewImports.cshtml
复制到Views/_ViewImports.cshtml
,Pages/_ViewStarts.cshtml
复制到Views/_ViewStarts .cshtml
.
这是一个项目结构:
关于c# - 如何在同一个项目中同时拥有 MVC 和 Razor 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70104933/