在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"]为红色显示
if(System.Web.HttpContext.Current.Session["UserName"]!=null && System.Web.HttpContext.Current.Session["UserName"].ToString() =="")
{
//操作
}
else
{
//跳转到登陆页面
}
错误信息是:
未将对象引用设置到对象的实例
System.Web.HttpContext.Current.Session["UserName"]为红色显示
System.Web.HttpContext.Current.Session["UserName"]==null
有些时候你判断不等于空的时候会认为有值,所以会出现 错误:
未将对象引用设置到对象的实例
{
if(Session["UPower"].ToString ()!="5) {
throw new ArgumentNullException() ;
}
else
{
}
}
catch
{
Response.Redirect (login.aspx);
Response.End ();
}
{
if(Session["UPower"].ToString ()!="5) {
throw new ArgumentNullException() ;
}
else
{
}
}
catch
{
Response.Redirect (login.aspx);
Response.End ();
}
try
{
if(System.Web.HttpContext.Current.Session["UserName"]!=null && System.Web.HttpContext.Current.Session["UserName"].ToString() =="")
{
//操作
}
else
{
//跳转到登陆页面
}}
catch
{
//跳转到登陆页面
}
if(System.Web.HttpContext.Current.Session["UserName"]!=null)
{
if (System.Web.HttpContext.Current.Session["UserName"].ToString() =="")
{
//操作
}
else
{
//跳转到登陆页面
}
}
else
{
//跳转到登陆页面
}
就用if (Session["UserName"]!= null)判断就可以、了