You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在MVC项目中添加Razor Page Component后路由404问题排查

解决MVC应用中Blazor路由页面404的问题

你遇到的404问题是因为缺少Blazor Server的宿主页面配置,以及未将Blazor路由请求导向宿主页面的端点映射。以下是需要补充的配置:

1. 创建Blazor宿主页面

在Pages目录下新建_Host.cshtml文件,内容如下:

@page "/"
@{
    Layout = "_Layout";
}

<component type="typeof(App)" render-mode="ServerPrerendered" />

注意:如果项目中没有App.razor根组件,需同步创建:
在项目根目录新建App.razor:

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

同时创建Shared/MainLayout.razor作为默认布局:

@inherits LayoutComponentBase

<div class="page">
    <div class="main">
        @Body
    </div>
</div>

2. 更新Program.cs的端点配置

在UseEndpoints中添加MapFallbackToPage,将Blazor路由请求导向宿主页面:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
    endpoints.MapBlazorHub();
    // 添加该行配置
    endpoints.MapFallbackToPage("/_Host");
});

3. 调整_Layout.cshtml中的脚本位置

将blazor.server.js脚本移到</body>标签之前,确保DOM加载完成后再加载Blazor脚本:

<!-- 原head内容 -->
</head>
<body>
    <!-- 页面主体内容 -->
    
    <script src="_framework/blazor.server.js"></script>
</body>
</html>

完成以上配置后,访问/test即可正常加载Blazor页面。MVC路由会优先处理控制器请求,当请求匹配Blazor的@page路由规则时,会自动 fallback到_Host页面,由Blazor框架接管路由处理。

内容的提问来源于stack exchange,提问作者Adam Shakhabov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:19