应特别注意要使用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");
}
}
}