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