加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在BaseController中获取/设置HttpContext会话方

发布时间:2020-12-16 04:03:48 所属栏目:asp.Net 来源:网络整理
导读:我在BaseController类中创建了Get / Set HttpContext会话方法,还创建了Mocked HttpContextBase并创建了Get / Set方法. 哪个是使用它的最佳方式. HomeController : BaseController { var value1 = GetDataFromSession("key1") SetDataInSession("key2",(objec
我在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;
     }
  }

解决方法

第二个似乎是最好的.虽然我可能会将这两个作为扩展方法写入 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已经是一个抽象类,可以在单元测试中轻松模拟.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读