I have an ASP.NET Core application with Razor pages and I want take advantages of MVC into it, so I add Controllers folder to it with Views and also services.AddMvc()
to startup and another endpoint to it, then tried to run if it works. Simply I run the project and I want to test if it return simple view and I add controller name and also action after the default address, but it shows me "This localhost page can’t be found".
Would you please help me how I config my app?
CodePudding user response:
If you want to add MVC to a Razor Page project:
1.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?}");
});
}
2.You need to add a folder called Controllers
and a folder called 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: