2013-04-16 35 views
0

我在我的Asp.NET代碼設置Session這樣的:訪問ASP.NET會話的背景

public class MyController : Controller 
{ 
    public ActionResult Index() 
    { 
     Session["AdminID"] = id; 

     return View(); 
    } 
} 

但現在我要訪問此Session的文件,該文件是不是在Controller該項目的背景。 這可能嗎?

S.th.像這樣:

public class MyClass 
{ 
    public int Foo() 
    { 
     return Session["AdminID"] 
    } 
} 
+0

你是什麼背景呢?後臺線程/工作者? – MikeSW

回答

3

使用HttpContext.Current.Session

using System.Web; 

// ... 

public int Foo() 
{ 
    return (int)HttpContext.Current.Session["AdminID"]; 
} 
+0

這種方法將代碼耦合到HttpContext和Session提供程序,因此它是不可測試的,並且它不會在http請求之外工作。更好的方法是將值直接注入/設置到對象中。這樣,代碼就不會在意數值從哪裏來,並且耦合也會減少。 – MikeSW

+0

@MikeSW我正在回答一個具體的問題。當然,更好的方法將是你所建議的方法,但我們不知道這些代碼將如何使用,甚至值得像你提出的那樣做。 – volpav

+1

我爲HttpContext.Current.Session創建了一個包裝器,我將其注入到控制器和輔助類中。它使單元測試更容易,因爲我可以在測試時傳入內存實現。 http://codingsmith.co.za/a-better-way-of-working-with-httpcontext-session-in-mvc/ – spaceman