[MVC]Asp.net MVC中的Session

[MVC]Asp.net MVC中的Session

2008年12月9日 分类: ASP.NET, ASP.NET MVC, C#, 开发笔记

最近使用ASP.NET MVC 中的Controller.Session对象时发现一个问题

原代码如下:

InformationController:

//网店控制器

ShopController shop = new ShopController();

UserInfo user = business.SelectById<UserInfo>(userId);

//查询用户

Session["User"] = user;

//图片信息

//定位到编辑图片信息页面

if (picture == 1)

{

return shop.EditProduct(identifier, modId);

}

//文字信息

if (picture == 2)

{

return shop.EditInfo(identifier, modId);

}

ShopController:

public ActionResult EditInfo(int identifier, int moduleId)

{

//如果登录用户为空则重定向到登录界面

if (null == Session["User"])

{

return RedirectToAction("Index", "User");

}

}

实现的功能就是,通过InfomationController赋值Session["User"]对象,然后调用ShopController的action

但是上述代码执行后,shopController中读取不到Session["User"]?!于是想到Session是MVC封装到

Controller的一个属性Session,因此将上述对Session["user"]的赋值只是针对informationController

而不是shopController,因此shopController读取不到Session["User"]所以出错

将代码改为:

InformationController:

//网店控制器

ShopController shop = new ShopController();

UserInfo user = business.SelectById<UserInfo>(userId);

//查询用户

shop.Session["User"] = user;

问题解决,但是还有个疑问就是为什么我用户登录的Session["User"]ShopController就能够调用呢?

看来需要看看MVC源码了

翻看了MVC的源码发现先前的修改是错的,同样是提示NullReferenceException

Controller的源码中Session属性的声明如下:

public HttpSessionStateBase Session {

get {

return HttpContext == null ? null : HttpContext.Session;

}

}

原来是只读属性,于是单步跟踪发现

ShopController shop= new ShopController();

创建后的Shop控制器的Session属性为Null,结果给Session["User"]赋值肯定报空指针异常,于是发现直接创建

Cotroller肯定不行,于是改用RedirectToAction()问题解决