刚做asp.net 没有多久,在判断用户是否登陆的代码中,我开始是这样写的:
if (Session["username"].ToString() == "")
{
Response.Redirect("Login.aspx");
}
出现编译错误:异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
查看帮助文档的时候才发现:If you attempt to use a nonexistent session state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.
在session没有存在的情况下,对它进行了操作,就会发生对象引用错误的异常.正确的写法应该是:
if (Session["City"] == null) { //判断是否正确; }
其实,在用其他的,像Cookies也是一样的道理吧.
|