2010-02-06 59 views
2

我正在做一個ASP.NET MVC應用程序,我的一些Action方法和其他擴展方法需要訪問用戶數據。我使用來獲取用戶的代碼是:在控制器和擴展方法中訪問ASP.NET MVC Session []數據的建議?

this.currentUser = (CurrentUser)HttpContext.Session["CurrentUser"]; 

//and in the extension methods it's: 

CurrentUser user = (CurrentUser)HttpContext.Current.Session["CurrentUser"]; 

這同一條線散落在我的很多控制器的很多我的行動方法之一。問題是這使得它很難測試,並且它看起來不是很「優雅」。

任何人都可以提出一個很好的SOLID方法來解決這個問題嗎?

感謝

戴夫

回答

6

您不應將用戶存儲在Session中。當通過修改web.config或達到內存限制重新啓動應用程序時,會話可能很容易丟失。這將在隨機時刻註銷用戶。

沒有理由不使用會話用於不同的目的(例如將項目存儲在購物籃中)。你可以那樣做:

首先我們定義的接口:

public interface ISessionWrapper 
{ 
    int SomeInteger { get; set; } 
} 

然後我們做的HttpContext執行:

public class HttpContextSessionWrapper : ISessionWrapper 
{ 
    private T GetFromSession<T>(string key) 
    { 
     return (T) HttpContext.Current.Session[key]; 
    } 

    private void SetInSession(string key, object value) 
    { 
     HttpContext.Current.Session[key] = value; 
    } 

    public int SomeInteger 
    { 
     get { return GetFromSession<int>("SomeInteger"); } 
     set { SetInSession("SomeInteger", value); } 
    } 
} 

然後我們定義我們的基本控制器:

public class BaseController : Controller 
{ 
    public ISessionWrapper SessionWrapper { get; set; } 

    public BaseController() 
    { 
     SessionWrapper = new HttpContextSessionWrapper(); 
    } 
} 

最後:

public ActionResult SomeAction(int myNum) 
{   
    SessionWrapper.SomeInteger 
} 

這將使測試變得簡單,因爲您可以用控制器測試中的模擬代替ISessionWrapper。

2

是。不要使用會話(有several reasons爲什麼不)。

Asp.Net有一個非常好的機制,稱爲Forms Authentication用於認證和訪問用戶數據。

我已經回答了a similar question這可能有幫助。

+0

我讀過你對另一個問題的回答,我還閱讀了REST介紹文章(非常好,內容翔實!),我會贊同所有提出的觀點。直到現在,我還沒有考慮將用戶數據視爲違反RESTful原則。我不能保證我會爲這個特定的應用程序採用這些原則(儘管我會將其作爲一種可能性進行研究),但我一定會努力在將來更加嚴格地遵守RESTful原則。 – DaveDev 2010-02-06 14:09:51

相關問題