Tuesday, March 19, 2013

HttpSessionState vs HttpSessionStateBase

ASP.NET MVC controllers have a Session variable of type HttpSessionStateBase. This is different from the Session variable available in Webform (in class Page) which is of type HttpSessionState.
The reason for introducing this new type of HttpSession is to improve testability since its easier to mock out HttpSessionStateBase.

However if you have an extension method for HttpSessionState that will be incompatible with an extension method for HttpSessionStateBase (and vice versa). You can work around this by making writing the extension method for MVC (i.e. HttpSessionStateBase) and then using HttpSessionStateWrapper for converting HttpSessionState to HttpSessionStateBase.

HttpSessionStateBase sessionBase = new HttpSessionStateWrapper(Page.Session);

Here is a sample example: