適用於 Azure Cache for Redis 的 ASP.NET 工作階段狀態提供者ASP.NET Session State Provider for Azure Cache for Redis

Azure Cache for Redis 提供工作階段狀態提供者,可讓您用來將記憶體內部工作階段狀態儲存在 Azure Cache for Redis 中,而不是 SQL Server 資料庫中。Azure Cache for Redis provides a session state provider that you can use to store your session state in-memory with Azure Cache for Redis instead of a SQL Server database. 若要使用快取工作階段狀態提供者,請先設定快取,再使用「Azure Cache for Redis 工作階段狀態 NuGet 套件」設定 ASP.NET 應用程式的快取。To use the caching session state provider, first configure your cache, and then configure your ASP.NET application for cache using the Azure Cache for Redis Session State NuGet package. 對於 ASP.NET Core 應用程式,請 在 ASP.NET Core 中讀取會話和狀態管理For ASP.NET Core applications, read Session and state management in ASP.NET Core.

在實際的雲端應用程式中,避免儲存使用者工作階段某種形式的狀態通常並非理想做法,但某些方法會比其他方法更加影響效能和延展性。It's often not practical in a real-world cloud app to avoid storing some form of state for a user session, but some approaches impact performance and scalability more than others. 如果您需要儲存狀態,最好的方法是將狀態的數量控制得較低,並將其儲存在 Cookie 中。If you have to store state, the best solution is to keep the amount of state small and store it in cookies. 如果此方法不可行,次佳的方法是使用 ASP.NET 工作階段狀態搭配提供者,進行分散式的記憶體中快取。If that isn't feasible, the next best solution is to use ASP.NET session state with a provider for distributed, in-memory cache. 從效能和延展性的觀點來看,最差的解決方法是使用資料庫備份的工作階段狀態提供者。The worst solution from a performance and scalability standpoint is to use a database backed session state provider. 本主題提供使用 Azure Cache for Redis 的 ASP.NET 工作階段狀態提供者的指引。This topic provides guidance on using the ASP.NET Session State Provider for Azure Cache for Redis. 如需其他工作階段狀態選項的相關資訊,請參閱 ASP.NET 工作階段狀態選項For information on other session state options, see ASP.NET Session State options.

將 ASP.NET 工作階段狀態儲存在快取中Store ASP.NET session state in the cache

若要在 Visual Studio 中使用「Azure Cache for Redis 工作階段狀態」NuGet 套件來設定用戶端應用程式,請從 [工具] 功能表中,依序按一下 [NuGet 套件管理員] 和 [套件管理員主控台] 。To configure a client application in Visual Studio using the Azure Cache for Redis Session State NuGet package, click NuGet Package Manager , Package Manager Console from the Tools menu.

Package Manager Console 視窗執行下列命令。Run the following command from the Package Manager Console window.

Install-Package Microsoft.Web.RedisSessionStateProvider

重要

如果您使用進階層的叢集功能,則必須使用 RedisSessionStateProvider 2.0.1 或更高版本,否則會擲回例外狀況。If you are using the clustering feature from the premium tier, you must use RedisSessionStateProvider 2.0.1 or higher or an exception is thrown. 移至 2.0.1 或更新版本是一項重大變更;如需詳細資訊,請參閱 v2.0.0 重大變更詳細資料 (英文)Moving to 2.0.1 or higher is a breaking change; for more information, see v2.0.0 Breaking Change Details. 此文章更新時,此套件的最新版本是 2.2.3。At the time of this article update, the current version of this package is 2.2.3.

「Redis 工作階段狀態提供者 NuGet 封裝」對「StackExchange.Redis.StrongName 封裝」有相依性。The Redis Session State Provider NuGet package has a dependency on the StackExchange.Redis.StrongName package. 如果 StackExchange.Redis.StrongName 封裝不在專案中,代表已經安裝。If the StackExchange.Redis.StrongName package is not present in your project, it is installed.

注意

除了強式名稱的 StackExchange.Redis.StrongName 封裝外,另外還有非強式名稱版本的 StackExchange.Redis。In addition to the strong-named StackExchange.Redis.StrongName package, there is also the StackExchange.Redis non-strong-named version. 如果您的專案使用非強式名稱的 StackExchange.Redis 版本,您必須將它解除安裝,否則專案中會發生命名衝突。If your project is using the non-strong-named StackExchange.Redis version you must uninstall it, otherwise you get naming conflicts in your project. 如需這些封裝的相關詳細資訊,請參閱 設定 .NET 快取用戶端For more information about these packages, see Configure .NET cache clients.

NuGet 封裝會下載和加入必要的組件參考,並將下列區段加入您的 web.config 檔案。The NuGet package downloads and adds the required assembly references and adds the following section into your web.config file. 此區段包含讓您的 ASP.NET 應用程式使用 Azure Cache for Redis 工作階段狀態提供者所需的設定。This section contains the required configuration for your ASP.NET application to use the Azure Cache for Redis Session State Provider.

<sessionState mode="Custom" customProvider="MySessionStateStore">
  <providers>
    <!-- Either use 'connectionString' OR 'settingsClassName' and 'settingsMethodName' OR use 'host','port','accessKey','ssl','connectionTimeoutInMilliseconds' and 'operationTimeoutInMilliseconds'. -->
    <!-- 'throwOnError','retryTimeoutInMilliseconds','databaseId' and 'applicationName' can be used with both options. -->
    <!--
      <add name="MySessionStateStore" 
        host = "127.0.0.1" [String]
        port = "" [number]
        accessKey = "" [String]
        ssl = "false" [true|false]
        throwOnError = "true" [true|false]
        retryTimeoutInMilliseconds = "5000" [number]
        databaseId = "0" [number]
        applicationName = "" [String]
        connectionTimeoutInMilliseconds = "5000" [number]
        operationTimeoutInMilliseconds = "1000" [number]
        connectionString = "<Valid StackExchange.Redis connection string>" [String]
        settingsClassName = "<Assembly qualified class name that contains settings method specified below. Which basically return 'connectionString' value>" [String]
        settingsMethodName = "<Settings method should be defined in settingsClass. It should be public, static, does not take any parameters and should have a return type of 'String', which is basically 'connectionString' value.>" [String]
        loggingClassName = "<Assembly qualified class name that contains logging method specified below>" [String]
        loggingMethodName = "<Logging method should be defined in loggingClass. It should be public, static, does not take any parameters and should have a return type of System.IO.TextWriter.>" [String]
        redisSerializerType = "<Assembly qualified class name that implements Microsoft.Web.Redis.ISerializer>" [String]
      />
    -->
    <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider"
         host=""
         accessKey=""
         ssl="true" />
  </providers>
</sessionState>

標示註解的區段可提供屬性的範例和每個屬性的範例設定。The commented section provides an example of the attributes and sample settings for each attribute.

以來自 Microsoft Azure 入口網站之快取刀鋒視窗的值來設定屬性,並視需要設定其他值。Configure the attributes with the values from your cache blade in the Microsoft Azure portal, and configure the other values as desired. 如需關於存取快取屬性的指示,請參閱設定 Azure Cache for Redis 設定For instructions on accessing your cache properties, see Configure Azure Cache for Redis settings.

  • 主機 – 指定您的快取端點。host – specify your cache endpoint.
  • –根據 TLS 設定,使用您的非 TLS/ssl 埠或 TLS/ssl 埠。port – use either your non-TLS/SSL port or your TLS/SSL port, depending on the TLS settings.
  • accessKey – 用於快取的主要或次要金鑰。accessKey – use either the primary or secondary key for your cache.
  • ssl –如果您想要使用 TLS 來保護快取/用戶端通訊,則為 true;否則為 false。ssl – true if you want to secure cache/client communications with TLS; otherwise false. 請務必指定正確的連接埠。Be sure to specify the correct port.
    • 新快取的非 TLS 埠預設為停用。The non-TLS port is disabled by default for new caches. 針對此設定指定 true,以使用 TLS 埠。Specify true for this setting to use the TLS port. 如需啟用非 TLS 埠的詳細資訊,請參閱設定快取主題中的「存取埠」一節。For more information about enabling the non-TLS port, see the Access Ports section in the Configure a cache topic.
  • throwOnError – true (如果您想在發生失敗時擲出例外狀況) 或 false (如果您想在作業失敗時為無訊息模式)。throwOnError – true if you want an exception to be thrown if there is a failure, or false if you want the operation to fail silently. 您可以核取靜態 Microsoft.Web.Redis.RedisSessionStateProvider.LastException 屬性以檢查失敗。You can check for a failure by checking the static Microsoft.Web.Redis.RedisSessionStateProvider.LastException property. 預設值是 true。The default is true.
  • retryTimeoutInMilliseconds – 會在此間隔期間 (以毫秒指定) 重試失敗的作業。retryTimeoutInMilliseconds – Operations that fail are retried during this interval, specified in milliseconds. 第一次重試會在 20 毫秒後發生,然後每秒進行重試,直到 retryTimeoutInMilliseconds 間隔到期為止。The first retry occurs after 20 milliseconds, and then retries occur every second until the retryTimeoutInMilliseconds interval expires. 緊接著此間隔之後,作業會進行最後一次重試。Immediately after this interval, the operation is retried one final time. 如果作業仍失敗,會視 throwOnError 設定將例外狀況擲回給呼叫者。If the operation still fails, the exception is thrown back to the caller, depending on the throwOnError setting. 預設值為 0,表示不會重試。The default value is 0, which means no retries.
  • databaseId – 指定快取輸出資料所使用的資料庫。databaseId – Specifies which database to use for cache output data. 若未指定,就會使用預設值 0。If not specified, the default value of 0 is used.
  • applicationName – 金鑰在 redis 中會儲存為 {<Application Name>_<Session ID>}_DataapplicationName – Keys are stored in redis as {<Application Name>_<Session ID>}_Data. 這個命名配置可讓多個應用程式共用同一個 Redis 執行個體。This naming scheme enables multiple applications to share the same Redis instance. 此參數是選擇性的,如果您未提供,將會使用預設值。This parameter is optional and if you do not provide it a default value is used.
  • connectionTimeoutInMilliseconds – 此設定可讓您覆寫 StackExchange.Redis 用戶端中的 connectTimeout 設定。connectionTimeoutInMilliseconds – This setting allows you to override the connectTimeout setting in the StackExchange.Redis client. 若未指定,將會使用預設的 connectTimeout 設定為 5000。If not specified, the default connectTimeout setting of 5000 is used. 如需詳細資訊,請參閱 StackExchange.Redis 設定模型(英文)。For more information, see StackExchange.Redis configuration model.
  • operationTimeoutInMilliseconds – 此設定可讓您覆寫 StackExchange.Redis 用戶端中的 syncTimeout 設定。operationTimeoutInMilliseconds – This setting allows you to override the syncTimeout setting in the StackExchange.Redis client. 若未指定,將會使用預設的 syncTimeout 設定為 1000。If not specified, the default syncTimeout setting of 1000 is used. 如需詳細資訊,請參閱 StackExchange.Redis 設定模型(英文)。For more information, see StackExchange.Redis configuration model.
  • redisSerializerType - 此設定可讓您為傳送到 Redis 的工作階段內容指定自訂序列化。redisSerializerType - This setting allows you to specify custom serialization of session content that is sent to Redis. 指定的類型必須實作 Microsoft.Web.Redis.ISerializer 且必須宣告公用無參數建構函式。The type specified must implement Microsoft.Web.Redis.ISerializer and must declare public parameterless constructor. 預設會使用 System.Runtime.Serialization.Formatters.Binary.BinaryFormatterBy default System.Runtime.Serialization.Formatters.Binary.BinaryFormatter is used.

如需這些屬性的相關詳細資訊,請參閱 發佈 Redis 的 ASP.NET 工作階段狀態提供者(英文) 上的原始部落格文章公告。For more information about these properties, see the original blog post announcement at Announcing ASP.NET Session State Provider for Redis.

別忘記備註您 web.config 中的標準 InProc 工作階段狀態提供者區段。Don’t forget to comment out the standard InProc session state provider section in your web.config.

<!-- <sessionState mode="InProc"
     customProvider="DefaultSessionProvider">
     <providers>
        <add name="DefaultSessionProvider"
              type="System.Web.Providers.DefaultSessionStateProvider,
                    System.Web.Providers, Version=1.0.0.0, Culture=neutral,
                    PublicKeyToken=31bf3856ad364e35"
              connectionStringName="DefaultConnection" />
      </providers>
</sessionState> -->

執行了這些步驟後,您的應用程式就會設定為使用 Azure Cache for Redis 工作階段狀態提供者。Once these steps are performed, your application is configured to use the Azure Cache for Redis Session State Provider. 當您在應用程式中使用工作階段狀態時,該狀態會儲存在 Azure Cache for Redis 執行個體中。When you use session state in your application, it is stored in an Azure Cache for Redis instance.

重要

儲存在快取中的資料必須可序列化,這一點與可以儲存在預設記憶體中 ASP.NET 工作階段狀態供應器的資料不同。Data stored in the cache must be serializable, unlike the data that can be stored in the default in-memory ASP.NET Session State Provider. 使用 Redis 的工作階段狀態提供者時,請確定儲存在工作階段狀態中的資料類型為可序列化。When the Session State Provider for Redis is used, be sure that the data types that are being stored in session state are serializable.

ASP.NET 工作階段狀態選項ASP.NET Session State options

  • 記憶體中工作階段狀態提供者 – 此提供者會將工作階段狀態儲存在記憶體中。In Memory Session State Provider - This provider stores the Session State in memory. 使用此提供者的好處是它既簡單又快速。The benefit of using this provider is it is simple and fast. 不過,您在使用記憶體中提供者時將無法調整 Web Apps,因為它不是分散式的。However you cannot scale your Web Apps if you are using in memory provider since it is not distributed.
  • SQL Server 工作階段狀態提供者 – 此提供者會將工作階段狀態儲存在 SQL Server 中。Sql Server Session State Provider - This provider stores the Session State in Sql Server. 如果您想要在永續性儲存體中儲存工作階段狀態,請使用此供應器。Use this provider if you want to store the Session state in persistent storage. 您可以調整您的 Web 應用程式,但將 SQL Server 用於工作階段,會對 Web 應用程式的效能造成影響。You can scale your Web App but using Sql Server for Session has a performance impact on your Web App. 您也可以使用此提供者搭配記憶體內部 OLTP 組態,協助改善效能。You can also use this provider with an In-Memory OLTP configuration to help improve performance.
  • 分散式記憶體中工作階段狀態提供者,例如 Azure Cache for Redis 工作階段狀態提供者 – 此提供者可讓您同時兼顧兩方面。Distributed In Memory Session State Provider such as Azure Cache for Redis Session State Provider - This provider gives you the best of both worlds. 您的 Web 應用程式可擁有簡單、快速而可調整的工作階段狀態供應器。Your Web App can have a simple, fast, and scalable Session State Provider. 因為此供應器會將工作階段狀態儲存在快取中,您的應用程式必須考量與分散式記憶體中快取 (例如暫時性網路失敗) 通訊時的所有相關特性。Because this provider stores the Session state in a Cache, your app has to take in consideration all the characteristics associated when talking to a Distributed In Memory Cache, such as transient network failures. 如需使用快取的最佳作法,請參閱 Microsoft 模式和作法 Azure 雲端應用程式設計和實作指引中的快取指引For best practices on using Cache, see Caching guidance from Microsoft Patterns & Practices Azure Cloud Application Design and Implementation Guidance.

如需工作階段狀態和其他最佳作法的相關詳細資訊,請參閱 Web 開發最佳作法 (使用 Azure 建置實際的雲端應用程式)(英文)。For more information about session state and other best practices, see Web Development Best Practices (Building Real-World Cloud Apps with Azure).

協力廠商會話狀態提供者Third-party session state providers

下一步Next steps

查看 Azure Cache for Redis 的 ASP.NET 輸出快取提供者Check out the ASP.NET Output Cache Provider for Azure Cache for Redis.