在BaseController中获取/设置HttpContext会话方法与Mocking HttpContextBase一起创建Get / Set方法

时间:2011-06-11 07:07:51

标签: asp.net-mvc session httpcontext

我在BaseController类中创建了Get / Set HttpContext会话方法,还创建了Mocked HttpContextBase并创建了Get / Set方法。

这是使用它的最佳方式。

    HomeController : BaseController
    {
        var value1 = GetDataFromSession("key1") 
        SetDataInSession("key2",(object)"key2Value");

        Or

        var value2 = SessionWrapper.GetFromSession("key3");
        GetFromSession.SetDataInSession("key4",(object)"key4Value");
    }

   public class BaseController : Controller
   {
       public  T GetDataFromSession<T>(string key)
       {
          return (T) HttpContext.Session[key];
       }

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

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

     public BaseController()
     {
       SessionWrapper = new HttpContextSessionWrapper();
     }
  }

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

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

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

2 个答案:

答案 0 :(得分:13)

第二个似乎是最好的。虽然我可能会将这两个作为扩展方法写入HttpSessionStateBase,而不是将它们放入基本控制器中。像这样:

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;
    }
}

然后在控制器,帮助器或具有HttpSessionStateBase实例的东西中使用它:

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

编写会话包装器在ASP.NET MVC中是无用的,因为框架提供的HttpSessionStateBase已经是一个抽象类,可以在单元测试中轻松模拟。

答案 1 :(得分:5)

对最新帖子的SetDataInSession方法稍作修正。在我看来,这是一个优雅的解决方案!感谢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;
        }
}
  • 首先创建这个类,然后记得在Controller类中引用它将调用这个方法的命名空间。

  • 获取会话值时:

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

必须是与会话中持久存在的对象的兼容类型。

相关问题