我正在创建一个 mvc 项目并使用 Unity 对其进行测试。
我创建了一个会话服务,它从上下文中获取和设置数据(见下文)
public class SessionService : ISessionService
{
private IConfiguration _Configuration;
private ILog _Log;
private HttpContext _Context;
private T GetSession<T>(string key)
{
return (T)HttpContext.Current.Session[key];
}
private void SetSession(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
public SessionService(HttpContext context, IConfiguration configuration, ILog log)
{
_Configuration = configuration;
_Log = log;
_Context = context;
}
public SessionModel SessionModel
{
get
{
if (GetSession<SessionModel>("SESSION_SESSIONMODEL") == null)
{
SetSession("SESSION_SESSIONMODEL", new SessionModel());
}
return GetSession<SessionModel>("SESSION_SESSIONMODEL");
}
set { SetSession("SESSION_SESSIONMODEL", value); }
}
}
在我的测试中,我正在模拟一个会话(如下所示)并将其发送给
_TestSessionService = new SessionService(HttpContext.Current, Configuration, _TestLog);
var httpRequest = new HttpRequest("", "", "");
var httpResponce = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer =
new HttpSessionStateContainer("id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
httpContext.Items["AspSession"] =
typeof(HttpSessionState)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
HttpContext.Current = httpContext;
这一切都适用于测试,但是当我运行 Web 应用程序时,统一失败,因为它没有通过 httcontect 发送到 sessionservice 类。
有人可以提供帮助甚至更好的是,提供一个完整的示例来展示如何最好地处理 mvc 中的会话以进行测试和应用程序使用?