我實現了一個會話的輔助來保存和檢索基於以下示例會話變量:(我嘗試儘量減少使用會話變量) Stackoverflow question爲什麼使用HttpContext工作的MVC 4會話幫助器和HttpContextBase不工作?
我使用MVC 4和麪向.NET 4.5的Visual Studio 2012。
我實現了一個setter。此一個採用HttpContextBase(即controller.HttpContext):
public class HttpContextBaseSessionHelper : ISessionHelper
{
private readonly HttpContextBase _context;
public HttpContextBaseSessionHelper(HttpContextBase context)
{
_context = context;
}
public T Get<T>(string key)
{
object value = _context.Session[key];
return value == null ? default(T) : (T)value;
}
public void Set<T>(string key, T value)
{
_context.Session[key] = value;
}
}
此實現使用HttpContext的(即System.Web.HttpContext.Current):
public class HttpContextSessionHelper : ISessionHelper
{
private readonly HttpContext _context;
public HttpContextSessionHelper(HttpContext context)
{
_context = context;
}
public T Get<T>(string key)
{
object value = _context.Session[key];
return value == null ? default(T) : (T)value;
}
public void Set<T>(string key, T value)
{
_context.Session[key] = value;
}
}
在控制器的HttpContext屬性的類型的HttpContextBase (Controller.HttpContext)。 我可以模擬(使用Moq)基於HttpContextBase的ISessionHelper。
我使用以下兩個控制器動作在正在運行的應用(未單元測試),以查看是否正確的值被設置和檢索到:利用上述動作時
public ActionResult SessionSet()
{
_sessionHelper.Set<string>("TestKey", "TestValue");
ViewBag.SessionValue = (string)HttpContext.Session["TestKey"];
return View();
}
public ActionResult SessionGet()
{
HttpContext.Session["TestKey"] = "TestValue";
ViewBag.SessionValue = _sessionHelper.Get<string>("TestKey");
return View();
}
此實現拋出一個NullReference異常:
_sessionHelper = new HttpContextBaseSessionHelper(HttpContext);
但這種實施工作得很好:
_sessionHelper = new HttpContextSessionHelper(System.Web.HttpContext.Current);
我的問題是爲什麼會發生這種情況?不應該使用HttpContextBase的實現工作和使用HttpContext的實現看到Controller.HttpContext返回一個HttpContextBase類型的問題?
非常好!我會照辦的。 –
如何在沒有會話的情況下管理認證/授權?即使您的SOA具有標識用戶的單獨簽名請求,您仍需要某種形式的基於會話的ID數據才能寫入請求,不是嗎? –
@Darin你可以發表一些例子或提示如何「完全擺脫任何ASP。NET會話從你的應用程序? –