会话变量的空引用异常

时间:2013-05-12 03:32:05

标签: asp.net

为什么我在这里获得了一个空的引用异常,因为回发后的Session [“Time”]变量,即使我已经在get请求中初始化了它。

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

namespace WebApplication4
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Time"] = DateTime.Now.ToString();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write(Session["Time"].ToString());
        }
    }
}

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

2 个答案:

答案 0 :(得分:0)

它不应该为null,我只测试了你的代码并返回DateTime.Now.ToString()。

也许在你的global.asax或应用程序的某个地方你正在清除或不存储会话变量。

答案 1 :(得分:-1)

很可能为null,因为您只在页面加载时设置它,但由于任何原因在PostBack上设置它,会话可以为null。可以过期,或者池回收并重置它等等

页面加载,从帖子后面可以有很长的时间距离。有人加载页面,去煮咖啡,然后回来按回车......会话在哪里?

if (!IsPostBack)
{
  Session["Time"] = DateTime.Now.ToString();
}
// else If is PostBack the `Session["Time"]` can be null !!!

也许你需要使用ViewState而不是会话

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["Time"] = DateTime.Now.ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(ViewState["Time"].ToString());
    }

或者检查会话是否为空!

相关问题