2

I want to use MVC, Razor Pages & Web API within the same project. How do I set the default page to go to a MVC view and not a Razor Page? The default page should go to ~/Views/ToDo/Index.cshtml and not ~/Pages/Index.cshtml.

public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Deleted for brevity ... app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=ToDo}/{action=Index}/{id?}"); }); } 
0

2 Answers 2

3

You can try to change the routing of Index.cshtml in razor page.

Here is a demo:

Pages/index.cshtml(When you want to go to Pages/index.cshtml,route need to be https://localhost:xxxx/Index1):

@page "Index1" @model xxxxxxx.IndexModel @{ ViewData["Title"] = "Index"; } <h1>Index</h1> 

/Views/ToDo/Index.cshtml:

@{ ViewData["Title"] = "Index"; } <h1>TodoIndex</h1> 

Startup.cs:

public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Deleted for brevity ... app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Todo}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } 

result: enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Yiyi You! The solution here is to rename the default Razor page @page "Index1". It doesn't matter if endpoints.MapRazorPages() is placed before or after endpoints.MapControllerRoute(...) and services.AddMvc() has the same implementation as services.AddControllersWithViews() & services.AddRazorPages() as documented here github.com/dotnet/aspnetcore/blob/…
0

The most obvious solution would be to delete or rename the actual file at /Pages/Index.cshtml. The only reason that a route "/" is created to it is because it exists. If you remove or rename the file, no route will be generated.

1 Comment

Obviously, I forgot that Index is the default page in Razor Pages, but I'm still puzzled as to why the order of the endpoints (MapRazorPages / MapControllerRoute) doesn't affect the selection of the default page.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.