Stephen Pham
Stephen Pham

Reputation: 1597

Set default page in ASP.NET Core 3.1 MVC+Razor Pages+Web API

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

Upvotes: 2

Views: 6721

Answers (2)

Mike Brind
Mike Brind

Reputation: 30035

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.

Upvotes: 0

Yiyi You
Yiyi You

Reputation: 18159

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

Upvotes: 3

Related Questions