在Asp.net中,我用PageBase页面来继承Page, 把很多公用方法都写在PageBase中,其他每个页面都继承PageBase. 在登陆时我设Session["UserName"]="a";  那么当我在其他页面执行添加删除等操作时,首先判断Session是否存在,不存在就跳到登陆页面。  可当Session不存在时就出现问题,弹出错误信息,而不跳到登陆页面,下面是在PageBase中的一段代码
if(System.Web.HttpContext.Current.Session["UserName"]!=null && System.Web.HttpContext.Current.Session["UserName"].ToString() =="")
{
//操作
}
else
{
                              //跳转到登陆页面
}
错误信息是:
未将对象引用设置到对象的实例
System.Web.HttpContext.Current.Session["UserName"]为红色显示

解决方案 »

  1.   

    用System.Web.HttpContext.Current.Session["UserName"]+"" ==""判断比较保险
      

  2.   

    呵呵,你试试写成
    System.Web.HttpContext.Current.Session["UserName"]==null
    有些时候你判断不等于空的时候会认为有值,所以会出现 错误:
    未将对象引用设置到对象的实例
      

  3.   

    try
    {
    if(Session["UPower"].ToString ()!="5) {
     throw new ArgumentNullException() ;
    }
    else
    {
                        
    }
    }
    catch
    {
    Response.Redirect (login.aspx);
    Response.End ();
    }
      

  4.   

    try
    {
    if(Session["UPower"].ToString ()!="5) {
     throw new ArgumentNullException() ;
    }
    else
    {
                        
    }
    }
    catch
    {
    Response.Redirect (login.aspx);
    Response.End ();
    }
      

  5.   

    可能根本就没有这个Session
    try
    {
      if(System.Web.HttpContext.Current.Session["UserName"]!=null &&     System.Web.HttpContext.Current.Session["UserName"].ToString() =="")
    {
    //操作
    }
    else
    {
                                  //跳转到登陆页面
    }}
    catch
    {
               //跳转到登陆页面
    }
      

  6.   

    如果为null,System.Web.HttpContext.Current.Session["UserName"]就不存在,当然也没办法判断他是不是为空
    if(System.Web.HttpContext.Current.Session["UserName"]!=null)
    {
       if (System.Web.HttpContext.Current.Session["UserName"].ToString() =="")
    {
    //操作
    }
    else
    {
                                  //跳转到登陆页面
    }
    }
    else
    {
                                  //跳转到登陆页面
    }
      

  7.   

    在没判断有没有Session["UserName"]之前是不能用.ToString()的,否则就会报你上面说的错
    就用if (Session["UserName"]!= null)判断就可以、了