Azure Redis 缓存的 ASP.NET 会话状态提供程序ASP.NET Session State Provider for Azure Cache for Redis

Azure Redis 缓存提供了一个会话状态提供程序,可使用该提供程序通过 Azure 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 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.

在实际云应用中避免存储某种形式的用户会话状态通常是不现实的,但某些方法相比其他方法而言,对性能和可伸缩性的影响更大。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 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

要使用 Azure Redis 缓存会话状态 NuGet 包在 Visual Studio 中配置客户端应用程序,请在“工具”菜单中依次单击“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 Breaking Change Details(2.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 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">
    <!-- 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 = "" [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"
         ssl="true" />

注释部分提供了属性及每个属性的示例设置的一个示例。The commented section provides an example of the attributes and sample settings for each attribute.

使用来自 Azure 门户中的缓存边栏选项卡的值配置属性,并根据需要配置其他值。Configure the attributes with the values from your cache blade in the Azure portal, and configure the other values as desired. 有关访问缓存属性的说明,请参阅配置 Azure Redis 缓存设置For instructions on accessing your cache properties, see Configure Azure Cache for Redis settings.

  • host - 指定缓存终结点。host - specify your cache endpoint.
  • port - 使用非 SSL 端口或 SSL 端口,具体取决于 SSL 设置。port - use either your non-SSL port or your SSL port, depending on the ssl settings.
  • accessKey - 使用缓存的主密钥或辅助密钥。accessKey - use either the primary or secondary key for your cache.
  • ssl - 如果要使用 SSL 保护缓存/客户端通信,则为 true;否则为 false。ssl - true if you want to secure cache/client communications with ssl; otherwise false. 请务必指定正确的端口。Be sure to specify the correct port.
    • 默认情况下,为新缓存禁用非 SSL 端口。The non-SSL port is disabled by default for new caches. 为此设置指定 true 可使用 SSL 端口。Specify true for this setting to use the SSL port. 有关启用非 SSL 端口的详细信息,请参阅配置缓存主题中的访问端口部分。For more information about enabling the non-SSL 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"
        <add name="DefaultSessionProvider"
                    System.Web.Providers, Version=, Culture=neutral,
              connectionStringName="DefaultConnection" />
</sessionState> -->

执行这些步骤后,应用程序已配置为使用 Azure Redis 缓存会话状态提供程序。Once these steps are performed, your application is configured to use the Azure Cache for Redis Session State Provider. 在应用程序中使用会话状态时,会话状态将存储在 Azure 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 应用。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 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 Development Best Practices (Building Real-World Cloud Apps with Azure)(Web 开发最佳做法(使用 Azure 构建实际的云应用))。For more information about session state and other best practices, see Web Development Best Practices (Building Real-World Cloud Apps with Azure).

后续步骤Next steps

请查看用于 Azure Redis 缓存的 ASP.NET 输出缓存提供程序Check out the ASP.NET Output Cache Provider for Azure Cache for Redis.