【问题标题】:Set default page in ASP.NET Core 3.1 MVC+Razor Pages+Web API在 ASP.NET Core 3.1 MVC+Razor Pages+Web API 中设置默认页面
【发布时间】:2021-03-01 06:38:38
【问题描述】:

我想在同一个项目中使用 MVC、Razor Pages 和 Web API。如何将默认页面设置为转到 MVC 视图而不是 Razor 页面?默认页面应该转到~/Views/ToDo/Index.cshtml 而不是~/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?}");
    });
}

【问题讨论】:

    标签: c# asp.net-core razor-pages asp.net-core-3.1


    【解决方案1】:

    您可以尝试更改剃须刀页面中Index.cshtml的路由。

    这是一个演示:

    Pages/index.cshtml(当你要去Pages/index.cshtml时,路由需要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();
                });
    }
    

    结果:

    【讨论】:

    • 谢谢你依依!此处的解决方案是重命名默认 Razor 页面 @page “Index1”。 endpoints.MapRazorPages() 放在 endpoints.MapControllerRoute(...) 之前还是之后都没有关系,并且 services.AddMvc() 与 services.AddControllersWithViews() 和 services.AddRazorPages() 具有相同的实现,如此处所述@ 987654323@
    【解决方案2】:

    最明显的解决方案是删除或重命名/Pages/Index.cshtml 的实际文件。为它创建路由"/" 的唯一原因是它存在。如果删除或重命名文件,则不会生成路由。

    【讨论】:

    • 显然,我忘记了Index是Razor Pages中的默认页面,但是我仍然对为什么端点的顺序(MapRazorPages / MapControllerRoute)不影响默认的选择感到困惑页面。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2021-04-28
    • 2021-12-29
    • 2018-04-05
    • 2020-11-23
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多