您的位置:首页 > 理论基础 > 计算机网络

.net System.Web.HttpContext.Current.Session 获取值出错(在Page继承类的构造函数中出错)

2012-05-29 10:12 716 查看
应特别注意要使用session必须要page_load方法执行以建立了page对象以后才有session的使用目标,此时先检测Session是否为Null再调用值是不会提示错误的。

如果直接在Page页面中定义一个全局变量取Session的值就会提示未设置实例的错误!使用Application,Cookie同理也需注意这个问题。

经常在基类的构造函数中获取用户的信息,比如Cookie、Session等,但Session在构造时却还不存在,不过在OnInit时就可读取Session值了。

public partial class BasePage : System.Web.UI.Page

{

public BasePage()

{

// 这里Session对象还未创建

if (System.Web.HttpContext.Current.Session == null)

{

System.Web.HttpContext.Current.Response.Write("Session Is Null");

}

else

{

System.Web.HttpContext.Current.Response.Write("Session Is Exist");

}

}

protected override void OnInit(EventArgs e)

{

base.OnInit(e);

// 这里就可以访问Session对象了

if (System.Web.HttpContext.Current.Session == null)

{

System.Web.HttpContext.Current.Response.Write("Session Is Null");

}

else

{

System.Web.HttpContext.Current.Response.Write("Session Is Exist");

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: