Best practice for accessing an HttpContext session outside the controller in a separate helper class

Is it good to access an HttpContext session outside the controller in a separate helper class?

=====================

If the controller takes full responsibility for receiving data from the session and passing it to the helper class

Example

HomeController : BaseController
{
    var value1 = Httpcontext.Session["key1"];
    var value2 = Httpcontext.Session["key2"];
    var val...
    CallAMethod(value1,value2,val...);
}

Or should he mock the HttpContextBase and use it as in the following?

HomeController : BaseController
{
    //Use Dependency Injection pattern
    CallAMethod(base.SessionWrapper);
}

Implementation of ISessionWrapper

public interface ISessionWrapper
{
     T GetFromSession<T>(string key);
     SetInSession(string key, object value);
}

public class HttpContextSessionWrapper : ISessionWrapper
{
   private T GetFromSession<T>(string key)
   {
      return (T) HttpContext.Session[key];
   }

   private void SetInSession(string key, object value)
   {
      HttpContext.Session[key] = value;
   }
}

public class BaseController : Controller
{
   public ISessionWrapper SessionWrapper { get; set; }

   public BaseController()
   {
      SessionWrapper = new HttpContextSessionWrapper();
   }
}
+3
source share
1 answer

Apparently, you want to have some testing ability in your code (after all this you risk creating ISessionWrapper).

Both approaches have ups and downs.


  • Direct use of HttpContext

    • Quick search

    • . Nemely - HttpContext. NET.


  • (ISessionWrapper):

    • " " HttpContext


, .

, , , .


( OP) , .

+1

All Articles