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

从ASP.NET WebForms迁移到Core后基类HttpContext为空的解决方法

问题解决:ASP.NET Core PageModel中HttpContext为null的异常

错误原因

ASP.NET Core中,PageModel的构造函数执行时,HttpContext尚未完成初始化绑定,此时直接访问HttpContext.Session会触发空引用异常。

修复方案

1. 调整生命周期方法(推荐)

将BindData的调用从构造函数移至页面处理器执行前的生命周期方法OnPageHandlerExecuting,此时HttpContext已可用:

public class BasePage : PageModel
{
    private readonly IConfiguration _configuration;
    private DAL _dal = new DAL();

    public BasePage(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public override void OnPageHandlerExecuting(PageHandlerExecutingContext context)
    {
        BindData();
        base.OnPageHandlerExecuting(context);
    }

    public void BindData()
    {
        // 统一Session键名,避免逻辑错误
        if (string.IsNullOrEmpty(HttpContext.Session.GetString("Session_DisplayName")))
        {
            HttpContext.Session.SetString("Session_DisplayName", "usera");
        }
    }
}

2. 确保会话服务已启用

ASP.NET Core默认不启用会话,需在Program.cs中添加会话服务配置:

var builder = WebApplication.CreateBuilder(args);

// 添加会话服务
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

builder.Services.AddRazorPages();

var app = builder.Build();

// 启用会话中间件(位置必须在UseRouting之后,UseAuthorization之前)
app.UseSession();

app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();

app.Run();

补充说明

  • 原代码中存在Session键名不一致问题(判断用Session_DisplayName,设置用_Session_DisplayName),需统一键名保证逻辑正确性。
  • 若需要异步操作,可改用重写InitializeAsync方法替代OnPageHandlerExecuting。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:17:18