ASP.Net MVC 3:在哪里处理会话丢失?
当我的会话丢失或重建我的项目时,我开始遇到错误,因为我的表单身份验证 cookie 仍然存在。
在 WebForms 中,我将使用与需要登录的页面关联的母版页来简单地检查会话。
我如何在 MVC 的一个位置执行此操作?我讨厌必须在控制器中的每个操作中检查会话状态。
另一方面,我也不能只应用全局过滤器,因为并非所有控制器都需要会话状态。
在我的布局视图中可能有可能吗?这是需要会话的页面唯一的共同点。
I've started bumping into errors when my session has been lost, or upon rebuilding my project, as my forms authentication cookie still lives on.
In WebForms I'd use the masterpage associated with pages which require login to simply check for the session.
How would I do this in one location in MVC ? I'd hate having to check for session state in every action in my controllers.
On the other hand I can't just apply a global filter either, since not all Controllers require session state.
Would it perhaps be possible in my layout view ? It's the only thing the pages which require session have in common.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以做的一件事是对确实需要会话状态的控制器进行子类化。这样您就可以在这个基本控制器上创建一个过滤器。这将允许您在一个地方完成这一切。另外,正如您所指出的,全局过滤器在这里不会帮助您,因为逻辑并不适用于每个控制器。
One thing you could do is to sub-class the controllers that do need session state. This way you could create a filter on just this base controller. This would allow you to do it all in one place. Plus, as you pointed out, a global filter won't help you here since the logic does not apply to every controller.
将其添加到会话开始。如果发生会话丢失,它也需要触发会话启动。你可以在那里处理它,如下所示:
add it to session start. if a session loss happens it needs to trigger a session start too. you can handle it in there as follows:
我同意 Steve 所提到的,但我建议使用全局过滤器,而不是为所有控制器创建基类。原因是每次创建新控制器时,您应该始终记住从基本控制器派生,否则您可能会在应用程序中遇到随机行为,这可能需要花费数小时的调试时间。当您停止开发一段时间然后再重新开始时,这一点尤其重要。
另外,另一个原因是“优先组合优于继承”原则。
I agree with what Steve has mentioned, but I suggest to use Global Filters instead of creating a base class for all your controllers. The reason for this is everytime you create a new controller, you should always remember to derive from the base controller or you may experience random behaviours in your application that may take you hours of debugging. This is especially important when you stop development for a while and then get back to it.
Also, another reason is the "Favour composition over inheritance" principle.