我在 BaseController 类中创建了 Get/Set HttpContext Session 方法,还模拟了 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;
}
}
Or
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 http://msdn.microsoft.com/en-us/library/system.web.httpsessionstatebase.aspx而不是将它们放入基本控制器中。像这样:
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
use it:
public ActionResult Index()
{
Session.SetDataInSession("key1", "value1");
string value = Session.GetDataFromSession<string>("key1");
...
}
编写会话包装器在 ASP.NET MVC 中毫无用处,因为HttpSessionStateBase
框架提供的已经是一个抽象类,可以在单元测试中轻松模拟。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)