適用於 Azure Redis 快取的 ASP.NET 輸出快取提供者ASP.NET Output Cache Provider for Azure Cache for Redis

Redis 輸出快取提供者為輸出快取資料的程序外儲存體機制。The Redis Output Cache Provider is an out-of-process storage mechanism for output cache data. 此資料特別適用於完整 HTTP 回應 (頁面輸出快取)。This data is specifically for full HTTP responses (page output caching). 提供者插入 ASP.NET 4 中導入的新輸出快取提供者擴充點。The provider plugs into the new output cache provider extensibility point that was introduced in ASP.NET 4. 對於 ASP.NET Core 應用程式,請 在 ASP.NET Core 中讀取回應快取。For ASP.NET Core applications, read Response caching in ASP.NET Core.

若要使用 Redis 輸出快取提供者,請先設定您的快取,然後使用「Redis 輸出快取提供者 NuGet 封裝」設定 ASP.NET 應用程式。To use the Redis Output Cache Provider, first configure your cache, and then configure your ASP.NET application using the Redis Output Cache Provider NuGet package. 本主題提供為使用 Redis 輸出快取提供者而進行應用程式設定的相關指引。This topic provides guidance on configuring your application to use the Redis Output Cache Provider. 如需有關建立及設定「Azure Redis 快取」執行個體的詳細資訊,請參閱建立快取For more information about creating and configuring an Azure Cache for Redis instance, see Create a cache.

將 ASP.NET 頁面輸出儲存在快取中Store ASP.NET page output 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.RedisOutputCacheProvider

「Redis 輸出快取提供者 NuGet 封裝」對「StackExchange.Redis.StrongName 封裝」有相依性。The Redis Output Cache 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. 如需「Redis 輸出快取提供者 NuGet 套件」的詳細資訊,請參閱 RedisOutputCacheProvider (英文) NuGet 頁面。For more information about the Redis Output Cache Provider NuGet package, see the RedisOutputCacheProvider NuGet page.

注意

除了強式名稱的 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. Redis 版本,您必須將它卸載;否則,您會在專案中遇到命名衝突。If your project is using the non-strong-named StackExchange.Redis version you must uninstall it; otherwise, you will experience 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 應用程式使用 Redis 輸出快取提供者所需的設定。This section contains the required configuration for your ASP.NET application to use the Redis Output Cache Provider.

<caching>
  <outputCache defaultProvider="MyRedisOutputCache">
    <providers>
      <add name="MyRedisOutputCache" type="Microsoft.Web.Redis.RedisOutputCacheProvider"
           host=""
           accessKey=""
           ssl="true" />
    </providers>
  </outputCache>
</caching>

以來自 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.

屬性Attribute 類型Type 預設Default 描述Description
主機host 字串string 主機"localhost" Redis 伺服器 IP 位址或主機名稱The Redis server IP address or host name
portport 正整數positive integer 6379 (非 TLS/SSL) 6379 (non-TLS/SSL)
6380 (TLS/SSL) 6380 (TLS/SSL)
Redis 伺服器埠Redis server port
accessKeyaccessKey 字串string """" 啟用 Redis 授權時的 Redis 伺服器密碼。Redis server password when Redis authorization is enabled. 預設值為空字串,表示會話狀態提供者在連線到 Redis 伺服器時,不會使用任何密碼。The value is empty string by default, which means the session state provider won’t use any password when connecting to Redis server. 如果您的 Redis 伺服器位於可公開存取的網路(例如 Azure Redis Cache)中,請務必啟用 Redis 授權以改善安全性,並提供安全的密碼。If your Redis server is in a publicly accessible network like Azure Redis Cache, be sure to enable Redis authorization to improve security, and provide a secure password.
Sslssl booleanboolean falsefalse 是否透過 TLS 連接到 Redis 伺服器。Whether to connect to Redis server via TLS. 此值預設為 false ,因為 Redis 不支援現成的 TLS。This value is false by default because Redis doesn’t support TLS out of the box. 如果您使用的 Azure Redis 快取支援現成的 SSL,請務必將此設定為 true,以提升安全性。If you are using Azure Redis Cache which supports SSL out of the box, be sure to set this to true to improve security.

新快取的非 TLS 埠預設為停用。The non-TLS port is disabled by default for new caches. 針對此設定指定 true ,以使用非 TLS 埠。Specify true for this setting to use the non-TLS port. 如需啟用非 TLS 埠的詳細資訊,請參閱設定快取主題中的「存取埠」一節。For more information about enabling the non-TLS port, see the Access Ports section in the Configure a cache topic.
databaseIdNumberdatabaseIdNumber 正整數positive integer 00 這個屬性只能透過 web.config 或 AppSettings 來指定。This attribute can be specified only through either web.config or AppSettings.

指定要使用的 Redis 資料庫。Specify which Redis database to use.
connectionTimeoutInMillisecondsconnectionTimeoutInMilliseconds 正整數positive integer 由 >stackexchange.redis Redis 提供。Provided by StackExchange.Redis 用來在建立 >stackexchange.redis. Redis. ConnectionMultiplexer 時設定 ConnectTimeoutUsed to set ConnectTimeout when creating StackExchange.Redis.ConnectionMultiplexer.
operationTimeoutInMillisecondsoperationTimeoutInMilliseconds 正整數positive integer 由 >stackexchange.redis Redis 提供。Provided by StackExchange.Redis 用來在建立 >stackexchange.redis. Redis. ConnectionMultiplexer 時設定 SyncTimeoutUsed to set SyncTimeout when creating StackExchange.Redis.ConnectionMultiplexer.
connectionString (有效的 >stackexchange.redis. Redis 連接字串) connectionString (Valid StackExchange.Redis connection string) 字串string n/an/a AppSettings 或 web.config 的參數參考,或其他有效的 >stackexchange.redis. Redis 連接字串。Either a parameter reference to AppSettings or web.config, or else a valid StackExchange.Redis connection string. 這個屬性可以提供 hostportAccessKeyssl 和其他 >stackexchange.redis Redis 屬性的值。This attribute can provide values for host, port, accessKey, ssl, and other StackExchange.Redis attributes. 若要深入瞭解 connectionString,請參閱 屬性附注一節中的 設定 connectionStringFor a closer look at connectionString, see Setting connectionString in the Attribute notes section.
settingsClassNamesettingsClassName
settingsMethodNamesettingsMethodName
字串string
字串string
n/an/a 這些屬性只能透過 web.config 或 AppSettings 來指定。These attributes can be specified only through either web.config or AppSettings.

使用這些屬性來提供連接字串。Use these attributes to provide a connection string. settingsClassName 應該是元件限定的類別名稱,其中包含 settingsMethodName 所指定的方法。settingsClassName should be an assembly qualified class name that contains the method specified by settingsMethodName.

SettingsMethodName 所指定的方法應該是 public、static 和 void (不採用任何) 的參數,其傳回型別為 stringThe method specified by settingsMethodName should be public, static, and void (not take any parameters), with a return type of string. 這個方法會傳回實際的連接字串。This method returns the actual connection string.
loggingClassNameloggingClassName
loggingMethodNameloggingMethodName
字串string
字串string
n/an/a 這些屬性只能透過 web.config 或 AppSettings 來指定。These attributes can be specified only through either web.config or AppSettings.

藉由提供會話狀態/輸出快取的記錄以及 >stackexchange.redis. Redis 的記錄,即可使用這些屬性來對應用程式進行偵錯工具。Use these attributes to debug your application by providing logs from Session State/Output Cache along with logs from StackExchange.Redis. loggingClassName 應該是元件限定的類別名稱,其中包含 loggingMethodName 所指定的方法。loggingClassName should be an assembly qualified class name that contains the method specified by loggingMethodName.

LoggingMethodName 所指定的方法應該是 public、static 和 void (不會採用任何) 的參數,且傳回型別 loggingMethodNameThe method specified by loggingMethodName should be public, static, and void (not take any parameters), with a return type of System.IO.TextWriter.
applicationNameapplicationName 字串string 目前進程的模組名稱,或 "/"The module name of the current process or "/" 僅限 SessionStateProviderSessionStateProvider only
這個屬性只能透過 web.config 或 AppSettings 來指定。This attribute can be specified only through either web.config or AppSettings.

要在 Redis 快取中使用的應用程式名稱前置詞。The app name prefix to use in Redis cache. 客戶可使用相同的 Redis 快取來進行不同的用途。The customer may use the same Redis cache for different purposes. 為確保工作階段金鑰不會衝突,可以在前面加上應用程式名稱。To insure that the session keys do not collide, it can be prefixed with the application name.
throwOnErrorthrowOnError booleanboolean truetrue 僅限 SessionStateProviderSessionStateProvider only
這個屬性只能透過 web.config 或 AppSettings 來指定。This attribute can be specified only through either web.config or AppSettings.

發生錯誤時,是否擲回例外狀況。Whether to throw an exception when an error occurs.

如需 throwOnError 的詳細資訊,請參閱 屬性附注一節中 throwOnError 的附注For more about throwOnError, see Notes on throwOnError in the Attribute notes section.
>Redis. >redissessionstateprovider. LastException>Microsoft.Web.Redis.RedisSessionStateProvider.LastException.
retryTimeoutInMillisecondsretryTimeoutInMilliseconds 正整數positive integer 50005000 僅限 SessionStateProviderSessionStateProvider only
這個屬性只能透過 web.config 或 AppSettings 來指定。This attribute can be specified only through either web.config or AppSettings.

作業失敗時要重試的時間長度。How long to retry when an operation fails. 如果這個值小於 operationTimeoutInMilliseconds,提供者將不會重試。If this value is less than operationTimeoutInMilliseconds, the provider will not retry.

如需 retryTimeoutInMilliseconds 的詳細資訊,請參閱 屬性附注一節中 retryTimeoutInMilliseconds 的附注For more about retryTimeoutInMilliseconds, see Notes on retryTimeoutInMilliseconds in the Attribute notes section.
redisSerializerTyperedisSerializerType 字串string n/an/a 指定 Redis 之類別的元件限定型別名稱。Specifies the assembly qualified type name of a class that implements Microsoft.Web.Redis. ISerializer,其中包含要序列化和還原序列化值的自訂邏輯。ISerializer and that contains the custom logic to serialize and deserialize the values. 如需詳細資訊,請參閱 屬性附注一節中的 關於 redisSerializerTypeFor more information, see About redisSerializerType in the Attribute notes section.

屬性附注Attribute notes

設定 connectionStringSetting connectionString

如果 AppSettings 中存在這類字串,則 connectionString 的值會當做索引鍵,以便從 AppSettings 提取實際的連接字串。The value of connectionString is used as key to fetch the actual connection string from AppSettings, if such a string exists in AppSettings. 如果在 AppSettings 中找不到, connectionString 的值將作為索引鍵,以從 web.config connectionString 區段提取實際的連接字串(如果該區段存在的話)。If not found inside AppSettings, the value of connectionString will be used as key to fetch actual connection string from the web.config ConnectionString section, if that section exists. 如果連接字串不存在於 AppSettings 或 web.config ConnectionString 區段中,則在建立 >stackexchange.redis. Redis. ConnectionMultiplexer 時, ConnectionString 的常值會用來做為連接字串。If the connection string does not exists in AppSettings or the web.config ConnectionString section, the literal value of connectionString will be used as the connection string when creating StackExchange.Redis.ConnectionMultiplexer.

下列範例說明如何使用 connectionStringThe following examples illustrate how connectionString is used.

範例 1Example 1

<connectionStrings>
    <add name="MyRedisConnectionString" connectionString="mycache.redis.cache.windows.net:6380,password=actual access key,ssl=True,abortConnect=False" />
</connectionStrings>

在中 web.config ,使用上述索引鍵做為參數值,而不是實際值。In web.config, use above key as parameter value instead of actual value.

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvide"
             name = "MySessionStateStore"
             connectionString = "MyRedisConnectionString"/>
    </providers>
</sessionState>

範例 2Example 2

<appSettings>
    <add key="MyRedisConnectionString" value="mycache.redis.cache.windows.net:6380,password=actual access key,ssl=True,abortConnect=False" />
</appSettings>

在中 web.config ,使用上述索引鍵做為參數值,而不是實際值。In web.config, use above key as parameter value instead of actual value.

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvide"
             name = "MySessionStateStore"
             connectionString = "MyRedisConnectionString"/>
    </providers>
</sessionState>

範例 3Example 3

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvide"
             name = "MySessionStateStore"
             connectionString = "mycache.redis.cache.windows.net:6380,password=actual access key,ssl=True,abortConnect=False"/>
    </providers>
</sessionState>

ThrowOnError 上的注意事項Notes on throwOnError

目前,如果會話作業期間發生錯誤,會話狀態提供者將會擲回例外狀況。Currently, if an error occurs during a session operation, the session state provider will throw an exception. 這會關閉應用程式。This shuts down the application.

此行為已經過修改,可支援現有 ASP.NET 會話狀態提供者使用者的期望,同時也提供在需要時處理例外狀況的能力。This behavior has been modified in a way that supports the expectations of existing ASP.NET session state provider users while also providing the ability to act on exceptions, if desired. 當發生錯誤時,預設行為仍然會擲回例外狀況,與其他 ASP.NET 會話狀態提供者一致;現有程式碼的運作方式應該與之前相同。The default behavior still throws an exception when an error occurs, consistent with other ASP.NET session state providers; existing code should work the same as before.

如果您將 throwOnError 設定為 false,則不會在錯誤發生時擲回例外狀況,而是會無訊息地失敗。If you set throwOnError to false, then instead of throwing an exception when an error occurs, it will fail silently. 若要查看是否有錯誤,如果有,請探索例外狀況,並檢查 Redis 的靜態屬性。 >redissessionstateprovider. LastExceptionTo see if there was an error and, if so, discover what the exception was, check the static property Microsoft.Web.Redis.RedisSessionStateProvider.LastException.

RetryTimeoutInMilliseconds 上的注意事項Notes on retryTimeoutInMilliseconds

這會提供一些重試邏輯,以簡化某些會話作業應該在失敗時重試的情況(因為網路問題),同時也可讓您控制重試超時或完全退出重試。This provides some retry logic to simplify the case where some session operation should retry on failure because of things like network glitch, while also allowing you to control the retry timeout or opt out of retry entirely.

如果您將 retryTimeoutInMilliseconds 設定為數字(例如2000),則當會話作業失敗時,將會重試2000毫秒,然後將它視為錯誤。If you set retryTimeoutInMilliseconds to a number, for example 2000, then when a session operation fails, it will retry for 2000 milliseconds before treating it as an error. 因此,若要讓會話狀態提供者套用此重試邏輯,只要設定 timeout 即可。So to have the session state provider to apply this retry logic, just configure the timeout. 第一次重試會在20毫秒後發生,這在大多數情況下都已足夠,因為發生網路問題。The first retry will happen after 20 milliseconds, which is sufficient in most cases when a network glitch happens. 之後它會每秒重試一次。在經過一段時間之後,它會再重試一次,以確保它不會在一秒的最) (的情況下減少。After that, it will retry every second until it times out. Right after the time out, it will retry one more time to make sure that it won’t cut off the timeout by (at most) one second.

如果您不認為需要重試 (例如,當您在與應用程式相同的電腦上執行 Redis 伺服器時) 或者,如果您想要自行處理重試邏輯,請將 retryTimeoutInMilliseconds 設定為0。If you don’t think you need retry (for example, when you are running the Redis server on the same machine as your application) or if you want to handle the retry logic yourself, set retryTimeoutInMilliseconds to 0.

關於 redisSerializerTypeAbout redisSerializerType

根據預設,將值儲存在 Redis 上的序列化會以 BinaryFormatter 類別所提供的二進位格式來完成。By default, the serialization to store the values on Redis is done in a binary format provided by the BinaryFormatter class. 使用 redisSerializerType 來指定類別的元件限定型別名稱,這個類別會 Redis ISerializer ,而且具有自訂邏輯來序列化和還原序列化值。Use redisSerializerType to specify the assembly qualified type name of a class that implements Microsoft.Web.Redis.ISerializer and has the custom logic to serialize and deserialize the values. 例如,以下是使用 JSON.NET 的 Json 序列化程式類別:For example, here is a Json serializer class using JSON.NET:

namespace MyCompany.Redis
{
    public class JsonSerializer : ISerializer
    {
        private static JsonSerializerSettings _settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };

        public byte[] Serialize(object data)
        {
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data, _settings));
        }

        public object Deserialize(byte[] data)
        {
            if (data == null)
            {
                return null;
            }
            return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), _settings);
        }
    }
}

假設這個類別是在名稱為 MyCompanyDll 的元件中定義,您可以將參數 redisSerializerType 設定為使用它:Assuming this class is defined in an assembly with name MyCompanyDll, you can set the parameter redisSerializerType to use it:

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvider"
             name = "MySessionStateStore"
             redisSerializerType = "MyCompany.Redis.JsonSerializer,MyCompanyDll"
             ... />
    </providers>
</sessionState>

Output cache 指示詞Output cache directive

將 OutputCache 指示詞新增至每一個您要快取輸出的頁面。Add an OutputCache directive to each page for which you wish to cache the output.

<%@ OutputCache Duration="60" VaryByParam="*" %>

在上一個範例中,已快取的頁面資料會留在快取中 60 秒,而且會對每一個參數組合快取不同版本的頁面。In the previous example, the cached page data remains in the cache for 60 seconds, and a different version of the page is cached for each parameter combination. 如需 OutputCache 指示詞的詳細資訊,請參閱 @OutputCacheFor more information about the OutputCache directive, see @OutputCache.

一旦執行這些步驟,您的應用程式將設定為使用 Redis 輸出快取提供者。Once these steps are performed, your application is configured to use the Redis Output Cache Provider.

協力廠商輸出快取提供者Third-party output cache providers

後續步驟Next steps

請參閱適用於 Azure Redis 快取的 ASP.NET 工作階段狀態提供者Check out the ASP.NET Session State Provider for Azure Cache for Redis.