MVC中如何使用Session?

來源:互聯網
上載者:User

標籤:http   io   ar   使用   sp   資料   on   問題   cti   

      ASP.NET平台作為底層的架構,它提供了HttpContext.Session這個成員屬性讓我們可以方便地使用Session,但是在MVC中,Controller抽象類別為也提供了這樣一個屬性,我們只要訪問它就可以了(支援更好的測試性)。

  SessionStateModule是根據當前HttpHandler來決定是不是啟用Session。但是現在Controller和Page是分開的, Controller又是如何使用Session的呢?要回答這個問題就要扯到路由了,簡單地說:現在在MVC處理請求的時候,當前HttpHandler是 MvcHandler類的執行個體,它有如下定義:

public class MvcHandler : IHttpAsyncHandler, IHttpHandler, IRequiresSessionState{    ...    protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state);    protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state);    protected internal virtual void EndProcessRequest(IAsyncResult asyncResult);    protected virtual void ProcessRequest(HttpContext httpContext);    protected internal virtual void ProcessRequest(HttpContextBase httpContext);    IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);    void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result);    void IHttpHandler.ProcessRequest(HttpContext httpContext);}

因此,在Controller.Session中,它是訪問的HttpContext.Session,而MvcHandler實現了IRequiresSessionState介面,所以,訪問HttpContext.Session就可以擷取到Session 。

在MVC中,還有一個地方也在使用Session,那就是Controller.TempData這個成員屬性。通常我們可能會這樣使用它:

TempData["MKey"] = "Any Message";return RedirectToAction("MyAction");

在這種地方,這些儲存到TempData的資料其實也是存放在Session中的。你可以從web.config中關閉Session,你就能看到異常了。對於這種使用方法,你仍然可以前面的替代方法,但是,還有另一種方法也能做為替代Session的方法。我們看一下Controller的一段代碼:

protected virtual ITempDataProvider CreateTempDataProvider(){    return new SessionStateTempDataProvider();}


SessionStateTempDataProvider內部實現:

public class SessionStateTempDataProvider : ITempDataProvider{    // Fields    internal const string TempDataSessionStateKey = "__ControllerTempData";    // Methods    public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext)    {        HttpSessionStateBase session = controllerContext.HttpContext.Session;        if (session != null)        {            Dictionary<string, object> dictionary = session["__ControllerTempData"] as Dictionary<string, object>;            if (dictionary != null)            {                session.Remove("__ControllerTempData");                return dictionary;            }        }        return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);    }    public virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)    {        if (controllerContext == null)        {            throw new ArgumentNullException("controllerContext");        }        HttpSessionStateBase session = controllerContext.HttpContext.Session;        bool flag = (values != null) && (values.Count > 0);        if (session == null)        {            if (flag)            {                throw new InvalidOperationException(MvcResources.SessionStateTempDataProvider_SessionStateDisabled);            }        }        else if (flag)        {            session["__ControllerTempData"] = values;        }        else if (session["__ControllerTempData"] != null)        {            session.Remove("__ControllerTempData");        }    }}

MVC中如何使用Session?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.