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

Man*_*kar 6 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");
    }
Run Code Online (Sandbox Code Playgroud)
   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;
       }
   }
Run Code Online (Sandbox Code Playgroud)

要么

  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;
     }
  }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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


小智 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;
        }
}
Run Code Online (Sandbox Code Playgroud)
  • 首先创建这个类,然后记住在Controller类中引用它将调用此方法的命名空间.

  • 获取会话值时:

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

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