回发时的 ASPX 会话状态空异常

ASPX Session State null exception on Postback

即使使用下面的简单代码,我似乎也无法在回发时读取会话变量:

Default.apsx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 

Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" AutoPostBack="true" Text="Button" />
    </form>
</body>
</html>

代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            varcheck(Session["MyVar"].ToString());
        }
    }

    protected void varcheck(string checker)
    {
        System.Diagnostics.Debug.WriteLine(checker);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string ret_val = "Return this on postback";
        Session["MyVar"] = ret_val; 

    }
}

我得到:

An exception of type 'System.NullReferenceException' occurred in App_Web_5mcbvlrk.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.

我错过了什么吗?不应该在单击按钮时设置会话变量并在回发时读取吗?是否需要全局设置?

这是因为当你点击按钮时它不会直接进入 Button1_Click 事件它从上到下所以它首先加载 Page_Load 然后它进入事件所以你应该进行检查

      if (IsPostBack && Session["MyVar"] != null)
        {
            varcheck(Session["MyVar"].ToString());
        }

如果 Session["MyVar"] 不是 null 因为它将在第一个 postback 中为 null 到它不会抛出异常

编辑 1

如果不想使用会话可以使用静态变量来存储数据

    public static string MyVar;
    protected void Page_Load(object sender, EventArgs e)
    {


    if (!string.IsNullOrWhiteSpace(MyVar))
    {
        varcheck(MyVar);
    }
}

你可以设置点击值

protected void Button1_Click(object sender, EventArgs e)
    {
      if (string.IsNullOrWhiteSpace(MyVar))
      {
        MyVar= "Return this on postback";
        varcheck(MyVar);

      }

    }