我在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已经是一个抽象类,可以在单元测试中轻松模拟.