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

.NET Core Web Page路由异常:继承类OnGet()未执行及视图复用问题

.NET Core Web Page问题解决方案

1. 修复路由执行异常:调用正确的OnGet方法

问题根源是方法重写语法不规范,基类OnGet未标记为可重写,子类方法未正确重写,导致运行时调用基类方法。

修改步骤:

  • 调整基类BasePageModel的OnGet为异步虚方法:
public class BasePageModel : PageModel
{
    // 其他代码保持不变

    public virtual async Task<IActionResult> OnGet()
    {
        return RedirectToPage("/Status/Error");
    }
}
  • 子类IndexModel的OnGet添加override关键字,确保重写基类方法:
public class IndexModel : BasePageModel
{
    // 其他代码保持不变

    public override async Task<IActionResult> OnGet()
    {
        var clientId = HttpContext.Session.Get<int>("ClientId");

        if (clientId > 0)
        {
            Client = HttpContext.Session.Get<IEnumerable<Client>>("Clients").FirstOrDefault(x => x.Id.Equals(clientId));
            return Page();
        }

        return RedirectToPage("/Status/Error");
    }
}

说明:C#中只有基类方法标记virtual,子类方法用override才能实现多态调用,确保路由系统执行子类的OnGet。同时统一异步方法签名,避免因返回值差异导致的方法隐藏问题。

2. 实现视图复用:复用BasePage/index.cshtml

提供三种可行方案:

方案一:直接指定视图路径

在IndexModel的OnGet方法中,返回Page时指定基类视图的完整路径:

return Page("/Shared/Components/BasePage/index");

或在IndexModel类上添加特性,默认使用该视图:

[Page("/Shared/Components/BasePage/index")]
public class IndexModel : BasePageModel
{
    // 类代码
}

方案二:引用基类视图为部分视图

如果需要保留子类视图的自定义内容,在Reporting/index.cshtml中引用基类视图:

@await Html.PartialAsync("/Shared/Components/BasePage/index.cshtml", Model)
<!-- 此处添加子类视图的专属内容 -->

方案三:将基类视图设为布局页

若BasePage/index.cshtml是通用页面框架,可将其作为布局页,在子类视图中指定:

@{
    Layout = "/Shared/Components/BasePage/index.cshtml";
}
<!-- 子类视图内容会嵌入到布局页的@RenderBody()位置 -->

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:45:00