Get/Set HttpContext Session Methods in BaseController vs Mocking HttpContextBase to create Get/Set methods

情到浓时终转凉″ 提交于 2019-12-02 21:20:11
Darin Dimitrov

The second one seems the best. Although I would probably write those two as extension methods to the HttpSessionStateBase instead of putting them into a base controller. Like this:

public static class SessionExtensions
{
    public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key)
    {
         return (T)session[key];
    }

    public static void SetDataInSession<T>(this HttpSessionStateBase session, string key, object value)
    {
         session[key] = value;
    }
}

and then inside the controllers, or helpers, or something that has an instance of HttpSessionStateBase use it:

public ActionResult Index()
{
    Session.SetDataInSession("key1", "value1");
    string value = Session.GetDataFromSession<string>("key1");
    ...
}

Writing session wrappers is useless in ASP.NET MVC as the HttpSessionStateBase provided by the framework is already an abstract class which could be easily mocked in unit tests.

Daniel Carvalho Melo

Just a little correction for the SetDataInSession method of the latest post. In my opinion, it´s a elegant solution! Thanks Darin Dimitrov.

public static class SessionExtensions
{
 public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key) {
            return (T)session[key];
        }

        public static void SetDataInSession(this HttpSessionStateBase session, string key, object value) {
            session[key] = value;
        }
}
  • First create this class, and after remember to refer its namespace in the Controller class that will call this methods.

  • When getting the session value:

string value = Session.GetDataFromSession<string>("key1");

The must be a compatible type with the object persisted in the session.

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