İngilizce dilinde oku

Aracılığıyla paylaş


SessionStateUtility Sınıf

Tanım

ASP.NET bir uygulamanın oturum bilgilerini yönetmek için oturum durumu modülleri ve oturum durumu deposu sağlayıcıları tarafından kullanılan yardımcı yöntemler sağlar. Bu sınıf devralınamaz.

C#
public static class SessionStateUtility
Devralma
SessionStateUtility

Örnekler

Aşağıdaki kod örneği, kullanarak oturum bilgilerini bellekte depolayan özel bir Hashtableoturum durumu modülü uygulamasını gösterir. Modülü, sınıfını SessionStateUtility kullanarak geçerli HttpContext ve SessionIDManageröğesine başvurur, geçerli HttpStaticObjectsCollectionöğesini alır ve ASP.NET uygulamasının Global.asax dosyasında tanımlanan Session_OnEnd olayını oluşturur. Bu uygulama eşzamanlı Web isteklerinin aynı oturum tanımlayıcısını kullanmasını engellemez.

C#
using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.Threading;
using System.Web.Configuration;
using System.Configuration;

namespace Samples.AspNet.SessionState
{

    public sealed class MySessionStateModule : IHttpModule, IDisposable
    {
        private Hashtable pSessionItems = new Hashtable();
        private Timer pTimer;
        private int pTimerSeconds = 10;
        private bool pInitialized = false;
        private int pTimeout;
        private HttpCookieMode pCookieMode = HttpCookieMode.UseCookies;
        private ReaderWriterLock pHashtableLock = new ReaderWriterLock();
        private ISessionIDManager pSessionIDManager;
        private SessionStateSection pConfig;

        // The SessionItem class is used to store data for a particular session along with
        // an expiration date and time. SessionItem objects are added to the local Hashtable
        // in the OnReleaseRequestState event handler and retrieved from the local Hashtable
        // in the OnAcquireRequestState event handler. The ExpireCallback method is called
        // periodically by the local Timer to check for all expired SessionItem objects in the
        // local Hashtable and remove them.

        private class SessionItem
        {
            internal SessionStateItemCollection Items;
            internal HttpStaticObjectsCollection StaticObjects;
            internal DateTime Expires;
        }

        //
        // IHttpModule.Init
        //

        public void Init(HttpApplication app)
        {
            // Add event handlers.
            app.AcquireRequestState += new EventHandler(this.OnAcquireRequestState);
            app.ReleaseRequestState += new EventHandler(this.OnReleaseRequestState);

            // Create a SessionIDManager.
            pSessionIDManager = new SessionIDManager();
            pSessionIDManager.Initialize();

            // If not already initialized, initialize timer and configuration.
            if (!pInitialized)
            {
                lock (typeof(MySessionStateModule))
                {
                    if (!pInitialized)
                    {
                        // Create a Timer to invoke the ExpireCallback method based on
                        // the pTimerSeconds value (e.g. every 10 seconds).

                        pTimer = new Timer(new TimerCallback(this.ExpireCallback),
                                           null,
                                           0,
                                           pTimerSeconds * 1000);

                        // Get the configuration section and set timeout and CookieMode values.
                        Configuration cfg =
                          WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                        pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");

                        pTimeout = (int)pConfig.Timeout.TotalMinutes;
                        pCookieMode = pConfig.Cookieless;

                        pInitialized = true;
                    }
                }
            }
        }

        //
        // IHttpModule.Dispose
        //

        public void Dispose()
        {
            if (pTimer != null)
            {
                this.pTimer.Dispose();
               ((IDisposable)pTimer).Dispose();
            }
        }

        //
        // Called periodically by the Timer created in the Init method to check for 
        // expired sessions and remove expired data.
        //

        void ExpireCallback(object state)
        {
            try
            {
                pHashtableLock.AcquireWriterLock(Int32.MaxValue);

                this.RemoveExpiredSessionData();
            }
            finally
            {
                pHashtableLock.ReleaseWriterLock();
            }
        }

        //
        // Recursivly remove expired session data from session collection.
        //
        private void RemoveExpiredSessionData()
        {
            string sessionID;

            foreach (DictionaryEntry entry in pSessionItems)
            {
                SessionItem item = (SessionItem)entry.Value;

                if ( DateTime.Compare(item.Expires, DateTime.Now)<=0 )
                {
                    sessionID = entry.Key.ToString();
                    pSessionItems.Remove(entry.Key);

                    HttpSessionStateContainer stateProvider =
                      new HttpSessionStateContainer(sessionID,
                                                   item.Items,
                                                   item.StaticObjects,
                                                   pTimeout,
                                                   false,
                                                   pCookieMode,
                                                   SessionStateMode.Custom,
                                                   false);

                    SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
                    this.RemoveExpiredSessionData();
                    break;
                }
            }
        }

        //
        // Event handler for HttpApplication.AcquireRequestState
        //

        private void OnAcquireRequestState(object source, EventArgs args)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;
            bool isNew = false;
            string sessionID;
            SessionItem sessionData = null;
            bool supportSessionIDReissue = true;

            pSessionIDManager.InitializeRequest(context, false, out supportSessionIDReissue);
            sessionID = pSessionIDManager.GetSessionID(context);

            if (sessionID != null)
            {
                try
                {
                    pHashtableLock.AcquireReaderLock(Int32.MaxValue);
                    sessionData = (SessionItem)pSessionItems[sessionID];

                    if (sessionData != null)
                       sessionData.Expires = DateTime.Now.AddMinutes(pTimeout);
                }
                finally
                {
                    pHashtableLock.ReleaseReaderLock();
                }
            }
            else
            {
                bool redirected, cookieAdded;

                sessionID = pSessionIDManager.CreateSessionID(context);
                pSessionIDManager.SaveSessionID(context, sessionID, out redirected, out cookieAdded);

                if (redirected)
                    return;
            }

            if (sessionData == null)
            {
                // Identify the session as a new session state instance. Create a new SessionItem
                // and add it to the local Hashtable.

                isNew = true;

                sessionData = new SessionItem();

                sessionData.Items = new SessionStateItemCollection();
                sessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(context);
                sessionData.Expires = DateTime.Now.AddMinutes(pTimeout);

                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);
                    pSessionItems[sessionID] = sessionData;
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                             new HttpSessionStateContainer(sessionID,
                                                          sessionData.Items,
                                                          sessionData.StaticObjects,
                                                          pTimeout,
                                                          isNew,
                                                          pCookieMode,
                                                          SessionStateMode.Custom,
                                                          false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }

        //
        // Event for Session_OnStart event in the Global.asax file.
        //

        public event EventHandler Start;

        //
        // Event handler for HttpApplication.ReleaseRequestState
        //

        private void OnReleaseRequestState(object source, EventArgs args)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;
            string sessionID;

            // Read the session state from the context
            HttpSessionStateContainer stateProvider =
              (HttpSessionStateContainer)(SessionStateUtility.GetHttpSessionStateFromContext(context));

            // If Session.Abandon() was called, remove the session data from the local Hashtable
            // and execute the Session_OnEnd event from the Global.asax file.
            if (stateProvider.IsAbandoned)
            {
                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);

                    sessionID = pSessionIDManager.GetSessionID(context);
                    pSessionItems.Remove(sessionID);
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }

                SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
            }

            SessionStateUtility.RemoveHttpSessionStateFromContext(context);
        }
    }
}

Bu özel oturum durumu modülünü bir ASP.NET uygulamasında kullanmak için, aşağıdaki örnekte gösterildiği gibi Web.config dosyasındaki mevcut SessionStateModule başvuruyu değiştirebilirsiniz.

<configuration>
  <system.web>
    <httpModules>
      <remove name="Session" />
      <add name="Session"
      type="Samples.AspNet.SessionState.MySessionStateModule" />
    </httpModules>
  </system.web>
</configuration>

Açıklamalar

sınıfı, SessionStateUtility oturum durumu modülü veya oturum durumu deposu sağlayıcısı tarafından kullanılan statik yardımcı yöntemleri sağlar. Uygulama geliştiricilerinin kodlarından bu yöntemleri çağırmaları gerekmez.

Aşağıdaki tabloda oturum durumu modülünün ve oturum durumu deposu sağlayıcısının yöntemleri nasıl kullandığı açıklanmaktadır.

Yöntem Kullanın
GetHttpSessionStateFromContext yöntemi Mevcut bir oturumun oturum bilgilerini almak veya yeni bir oturum için oturum bilgileri oluşturmak için özel oturum durumu modülleri tarafından kullanılabilir.
AddHttpSessionStateToContext yöntemi Oturum verilerini geçerliye HttpContext eklemek ve özelliği aracılığıyla uygulama kodunun kullanımına açmak için oturum durumu modülü tarafından çağrılır Session .
RemoveHttpSessionStateFromContext yöntemi Geçerli HttpContextöğesinden oturum verilerini temizlemek için isteğin sonundaki veya EndRequest olayları sırasında ReleaseRequestState oturum durumu modülü tarafından çağrılır.
GetSessionStaticObjects yöntemi Global.asax dosyasında tanımlanan nesnelere göre koleksiyona başvuru almak için StaticObjects oturum durumu modülü tarafından çağrılır. Döndürülen HttpStaticObjectsCollection koleksiyon, geçerli HttpContextöğesine eklenen oturum verilerine eklenir.

Oturum verileri öğesine geçirilir ve geçerli HttpContext olandan bir nesne veya arabirimin IHttpSessionState geçerli herhangi bir HttpSessionStateContainer uygulaması olarak alınır.

Oturum durumu deposu sağlayıcısı uygulama hakkında bilgi için bkz. Session-State Deposu Sağlayıcısı Uygulama.

Özellikler

SerializationSurrogateSelector

Oturum serileştirme özelleştirmesi için kullanılan bir serileştirme vekil seçicisi alır veya ayarlar.

Yöntemler

AddHttpSessionStateToContext(HttpContext, IHttpSessionState)

Oturum verilerini geçerli isteğin bağlamı için uygular.

GetHttpSessionStateFromContext(HttpContext)

Geçerli isteğin bağlamından oturum verilerini alır.

GetSessionStaticObjects(HttpContext)

Belirtilen bağlam için statik nesneler koleksiyonuna başvuru alır.

IsSessionStateReadOnly(HttpContext)

Oturum durumunun belirtilen HttpContextiçin salt okunur olup olmadığını gösteren bir değer alır.

IsSessionStateRequired(HttpContext)

Belirtilen HttpContextiçin oturum durumunun gerekli olup olmadığını gösteren bir değer alır.

RaiseSessionEnd(IHttpSessionState, Object, EventArgs)

ASP.NET uygulaması için Global.asax dosyasında tanımlanan Session_OnEnd olayını yürütür.

RemoveHttpSessionStateFromContext(HttpContext)

Belirtilen bağlamdan oturum verilerini kaldırır.

Şunlara uygulanır

Ürün Sürümler
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

Ayrıca bkz.