Asp.net mvc如果解决Iframe、Frameset 中Session、Cookie丢失的问题。

      今天做项目的时候遇到这个问题,情形大概是这样,就是在一个创建页面里需要弹出一个窗口,而这个窗口是通过js方式创建Iframe来加载数据的。大家应该知道,默认情况下,Iframe、Frameset会重新开启新的进程,也就是无法获取当前用户的session、cookie信息。可是项目又要求必须获取,怎么办呢?

 

      在网上搜索资料,找到一个还不错的解决方案,如下:

请注意一下第1条,也就是说如果你通过cookie来传递值的话,请不要设置cookie的超时时间,否则,即使你加了P3P的http头也无法正常获取值。

 

可是就是在这种情况,我的问题依然无法得到解决,在BaseController中,怎么都获取不到Cookie的值。后来在google上搜索,找到一篇文章,

 

Andrei is right - it is null because when running under the ASP.NET MVC framework, the HttpContext (and therefore HttpContext.Session) is not set when the controller class is contructed as you might expect, but it set ("injected") later by the ControllerBuilder class. If you want a better understanding of the lifecycle you can either pull down the ASP.NET MVC framework (the source is available), or refer to: this page

If you need to access the Session then one way would be to override the "OnActionExecuting" method and access it there, as it will be available by that time.

However, as Andrei is suggesting, if your code is reliant on the Session then it could potentially be difficult to write unit tests, so perhaps you could consider wrapping the Session in a helper class which can then be swapped out for a different, non-web version when running under unit tests, therefore de-coupling your controller from the web.

原文链接:http://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors

 

后来我在BaseController中重写了OnActionExcuting这个方法,就可以正常获取了。希望我的这个文章能给其他类似问题的人一些帮助。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值