//源页中用来保存用户名到会话状态并重定向到目标页的代码如下:protected void SubmitButton_Click(object sender, EventArgs e){    this.Session["UserName"] = this.UserNameTextBox.Text;    this.Response.Redirect("DestinationPage.aspx");} //目标页中获取保存在会话状态中的用户名的代码如下:
 
protected void Page_Load(object sender, EventArgs e){    string UserName = this.Session["UserName"].ToString();    this.Response.Write(UserName);} 
我使用这种传递方式怎么总是出错啊?如下:
未将对象引用设置到对象的实例。 
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。

解决方案 »

  1.   

    string UserName = this.Session["UserName"].ToString();“this.Session["UserName"]”这个有默认20分钟的存活期,过20分它就失效啦,亲
      

  2.   

    修改如下string UserName = this.Session["UserName"]==null?"":this.Session["UserName"].ToString();
      

  3.   


    if(this.Session["UserName"]!=null)
    {
       string UserName = this.Session["UserName"].ToString();    this.Response.Write(UserName);}
    else
    {this.Response.Write("session会话失效");
    }
      

  4.   

    你的this.Session["UserName"]不存在时,会出现这种错误,
    但按你的这种写法Session["UserName"]应不会为空的可以这样写string UserName=Convert.ToString(this.Session["UserName"]);
    这样就不会有你那种错误了
      

  5.   

    你在使用Session["UserName"]之前,首先需要赋值的!!!