rfvn 发表于 2014-1-23 09:01:52

Session读取时报错:未将对象引用实例化

我的代码:

userController中的登录方法中:

Boolean result= _userService.ValidUser(userName, pwd, out msg);
if (result && msg == string.Empty)
{
Session["isLogin"] = "True";
return RedirectToAction("Index", "Manage");
}
else
{
Session["isLogin"] = "False";
return Json(false);
}

在ManageController里面,我原本想用一个只读变量去保存session["isLogin"]的值,因此我在Managecontroller的实例化方法中赋值:

private readonly bool LogOnState;

public ManageController(IModulesService modulesService)
{
_modulesService = modulesService;

if(Session["isLogin"]==null||Session["isLogin"].toString()=="false")

{

LogOnState=false;

}

else if(Session["isLogin"]!=null&&Session["isLogin"].toString()=="True")

{

LogOnState=true;

}
}

之后打开页面时就可以判定登录状态LogOnState=true,才打开页面



但是在运行到红色那行代码时,报错:未将引用对象实例化



后来我把判定session值的代码放入其他Action方法中使用就没报此错误。

总结:一般情况下通过这种方式获取Session值不会有问题,不过应特别注意要使用session必须要page_load方法执行以建立了page对象以后才有session的使用目标,此时先检测Session是否为Null再调用值是不会提示错误的。



页: [1]
查看完整版本: Session读取时报错:未将对象引用实例化