SessionIDManager.CreateSessionID(HttpContext) 方法

定義

建立工作階段的唯一工作階段識別項。

public:
 virtual System::String ^ CreateSessionID(System::Web::HttpContext ^ context);
public virtual string CreateSessionID (System.Web.HttpContext context);
abstract member CreateSessionID : System.Web.HttpContext -> string
override this.CreateSessionID : System.Web.HttpContext -> string
Public Overridable Function CreateSessionID (context As HttpContext) As String

參數

context
HttpContext

目前的 HttpContext 物件,參考用於處理 HTTP 要求 (例如,RequestResponse 屬性) 的伺服器物件。

傳回

String

唯一工作階段識別項。

實作

範例

下列程式碼範例示範繼承 類別的 SessionIDManager 類別,並使用提供和驗證 Guid 做為 SessionID 的方法覆寫 CreateSessionIDValidate 方法。

using System;
using System.Configuration;
using System.Web.Configuration;
using System.Web;
using System.Web.SessionState;

namespace Samples.AspNet.Session
{

  public class GuidSessionIDManager : SessionIDManager
  {

    public override string CreateSessionID(HttpContext context)
    {
      return Guid.NewGuid().ToString();
    }

    public override bool Validate(string id)
    {
      try
      {
        Guid testGuid = new Guid(id);

        if (id == testGuid.ToString())
          return true;
      }
      catch
      {
      }

      return false;
    }
  }
}
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Web
Imports System.Web.SessionState


Namespace Samples.AspNet.Session

  Public Class GuidSessionIDManager
    Inherits SessionIDManager

    Public Overrides Function CreateSessionID(context As HttpContext) As String
      Return Guid.NewGuid().ToString()
    End Function

    Public Overrides Function Validate(id As String) As Boolean
      Try
        Dim testGuid As Guid = New Guid(id)

        If id = testGuid.ToString() Then _
          Return True
      Catch
      
      End Try

      Return False
    End Function

  End Class

End Namespace

若要使用此範例中示範的自訂類別,請設定sessionState 元素的 sessionIDManagerType 屬性, (ASP.NET 設定 Schema) 元素,如下列範例所示。

<sessionState
  Mode="InProc"
  stateConnectionString="tcp=127.0.0.1:42424"
  stateNetworkTimeout="10"
  sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
  sqlCommandTimeout="30"
  customProvider=""
  cookieless="false"
  regenerateExpiredSessionId="false"
  timeout="20"
  sessionIDManagerType="Your.ID.Manager.Type,
    CustomAssemblyNameInBinFolder"
/>

備註

這個方法並非要從應用程式程式碼呼叫。

方法 CreateSessionID 會傳回唯一的會話識別碼,此識別碼是隨機產生的數位,編碼為 24 個字元字串,其中包含從 到 z 的小寫字元,以及從 0 到 5 的數位。

給繼承者的注意事項

您可以藉由建立繼承 SessionIDManager 類別的類別,並使用您自己的自訂實作覆 CreateSessionID(HttpContext) 寫 和 Validate(String) 方法,來提供 ASP.NET 會話狀態要使用的自訂會話識別碼。 如果您的自訂會話識別碼不符合方法預設實作所強制執行的 Validate(String) 字元條件約束,您應該覆寫 Validate(String) 方法,以提供自訂會話識別碼的驗證。 在此情況下,類別 SessionIDManager 會確保自訂會話識別碼是以 HTTP 回應編碼的 URL,以及分別使用 Encode(String)Decode(String) 方法從 HTTP 要求解碼的 URL。

適用於

另請參閱