2013-04-17 31 views
2

我實現了一個會話的輔助來保存和檢索基於以下示例會話變量:(我嘗試儘量減少使用會話變量) 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類型的問題?

回答

1

此實現使用上述動作 時拋出一個NullReference異常:

_sessionHelper =新HttpContextBaseSessionHelper(HttpContext的);

您已將此代碼放置在您的控制器的構造函數中,對嗎?這是行不通的,因爲在此階段HttpContext屬性尚未初始化。

protected override void Initialize(RequestContext requestContext) 
{ 
    base.Initialize(requestContext); 
    _sessionHelper = new HttpContextBaseSessionHelper(HttpContext); 
} 

備註關於從你的問題如下語句:

我嘗試使用會話變量的減少,如果你想訪問任何HttpContext的相關屬​​性,你應該把這個代碼在Initialize方法

您不應該試圖最小化會話變量的使用。你應該嘗試從應用程序中徹底擺脫任何ASP.NET會話。

+0

非常好!我會照辦的。 –

+0

如何在沒有會話的情況下管理認證/授權?即使您的SOA具有標識用戶的單獨簽名請求,您仍需要某種形式的基於會話的ID數據才能寫入請求,不是嗎? –

+0

@Darin你可以發表一些例子或提示如何「完全擺脫任何ASP。NET會話從你的應用程序? –