How should I integrate session state into an ASP.NET MVC application?

ぃ、小莉子 提交于 2019-12-03 13:56:45

Although there is nothing, in principle, wrong with using Session in ASP.NET MVC applications (well, at least nothing more wrong than using it in other ASP.NET applications...), I tend to feel it should be a last resort, when other things don't work.

Although your question is, generally, very well-written, you don't go into any great detail on what you propose to store in Session. The two examples I found in your question are:

  • Current user e-mail
  • partnerid

The user's e-mail address is already available from forms authentication, if you are using that, and can be added to other ASP.NET membership providers which don't already support it. It's not clear what partnerid actually is, but I'm skeptical that the Session is the only possible place to store it.

On the other hand, it's entirely possible that you need to store stuff you haven't told us about which would really only fit in the session.

So before you go too far down this road, make sure that other solutions are not already available for the data you need to store.

As for unit testing, you will need a fake HttpContext object (extend from HttpContextBase) and a fake session object (extend from SessionStateBase). Or you can do what we do, and use Phil Haacks HttpSimulator. Not a perfect solution, but there are so many tightly coupled objects that get wired together when you do anything with asp that you wont ever really find anything particularly elegant. We found we kept bumping into it so much that it was worth it to grab those classes and stick them in a helper library.

Cookies work by domain, so there isn't really any problems around that. You can always configure session to be in-proc as well and cookieless.

In general, be very sparse with what you keep in the session. But that goes for Webforms as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!