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

VS2019 WebForms项目Global.asax.cs的Session_Start事件不触发如何解决

问题解决步骤

问题根因

Session_Start事件未触发主要是Session状态模块未正确加载、事件无法被ASP.NET管道调用、页面Session功能被禁用三类原因导致,按以下步骤逐一排查即可解决:


解决方法

  1. 修正Session_Start事件的访问修饰符

    你当前代码中Session_Start未指定访问修饰符,默认是私有方法,ASP.NET运行时管道无法调用该方法。将方法修改为protected修饰即可:

    protected void Session_Start(object sender, EventArgs e)
    {
        Session["test"] = "123";
    }
    
  2. 确认Web.config中Session状态已开启

    检查项目根目录下Web.config的<system.web>节点,确保Session配置为开启状态,示例配置如下:

    <system.web>
      <!-- 开启Session状态,使用进程内模式,超时时间20分钟 -->
      <sessionState mode="InProc" cookieless="false" timeout="20" />
      <!-- 集成模式下需要配置该属性确保托管模块处理所有请求 -->
      <modules runAllManagedModulesForAllRequests="true">
      </modules>
    </system.web>
    

    如果sessionState的mode属性设置为Off,Session功能会被全局禁用,自然不会触发Session_Start事件。

  3. 确认页面未禁用Session功能

    检查Default.aspx页面顶部的Page指令,确保没有设置EnableSessionState="False",如果需要使用Session,该属性可以设置为True或者不填(默认值为True):

    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="webApp.Default" EnableSessionState="True" %>
    
  4. 空值防护(可选优化)

    为了避免应用重启、Session过期等极端情况出现空引用异常,建议读取值前先做非空判断:

    protected void Page_Load(object sender, EventArgs e)
    {
        string test = Application["test"]?.ToString() ?? "默认值";
        string test1 = Session["test"]?.ToString() ?? "默认值";
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:18:03