ASP.NET MVC 使用Redis共享Session

储存模式

1.InProc模式 
这是ASP.NET默认的Session管理模式,在应用进程内维护Session。

2.StateServer模式 
这是在服务器装了.NET环境后自带的一个StateServer服务,在应用进程外管理Session,可以进行多应用间的Session共享。

3.SQLServer模式 
这是利用SQLServer进行Session的托管。其优点在于可以利用SQLServer的优势处理海量Session,在应用进程外、可持久化、安全性高等优点。

4.Custom模式 
这是自定义模式,发挥空间很大,在拥有Provider的情况下,可以利用这一模式进行发挥,利用各种各样的数据存储程序进行Session管理。

InProc模式是默认的使用模式比较适合单应用。 
StateServer模式还需要配置注册表; 
SQLServer模式使用MS的DB;

如果是多台服务器还是有SessionID的问题;缺点都是使用MS定制,不能跨语言。Custom模式 比较适合结合第三方的Provider如Redis,Memecache,Mongodb 
适用与多台服务负载Session共享的场景,因为MVC下本身木有viewstate这些,不需要配置machinekey,如果使用SqlServer或StateServer会话模式解决SessionID不一致的问题(之前是反射修改一致或创建同样的ID)

基于Redis实现

因为基于Redis的实现Harbour.RedisSessionStateStore依赖于ServiceStack.Redis 说是4.x的版本有请求数限制,所以选择了Microsoft.Web.RedisSessionStateProvider,使用也比较简单 
PM> Install-Package Microsoft.Web.RedisSessionStateProvider

复制代码
<sessionState mode="Custom" customProvider="RedisSessionStateStore">
      <providers>
        <!-- Either use 'connectionString' and provide all parameters as string OR use 'host','port','accessKey','ssl','connectionTimeoutInMilliseconds' and 'operationTimeoutInMilliseconds'. -->
        <!-- 'throwOnError','retryTimeoutInMilliseconds','databaseId' and 'applicationName' can be used with both options. -->
        <!--
          <add name="RedisSessionStateStore" 
            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]
            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]
          />
        -->
        <add name="RedisSessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="xxx.xxx.xxx.xxx" accessKey="" ssl="false" />
      </providers>
    </sessionState>
复制代码

另外确保配置了Cookies的Domain

<httpCookies domain=".xxx.com" httpOnlyCookies="true"/>

销毁Session

复制代码
        /// <summary>
        /// 用户登出
         /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult SignOut(string returnUrl)
        {
            //清除Session
            Session.Abandon();
            Session.Clear();
            //清除自动登录Cookie
            var cookie = Request.Cookies[ConstantKey.autoLoginKey];
            if (cookie != null)
            {
                cookie.Domain = ".xxx.com";
                cookie.HttpOnly = true;
                cookie.Expires = DateTime.Now.AddDays(-24);
                Response.AppendCookie(cookie);
            }
            return RedirectToLocal(returnUrl);
        }
复制代码

!!!其他注意点

SessionId 不一致问题 
PRB:如果您使用 SqlServer 或 StateServer 会话模式 Web 场中会丢失会话状态 
https://support.microsoft.com/zh-cn/kb/325056 
趣谈StateServer在Web Garden,Web Farm下的使用 
www.cnblogs.com/UliiAn/p/3463720.html 
ASP.NET 负载均衡 StateServer Session共享问题 
http://www.cnblogs.com/ryhan/p/3748976.html

Cookies的Domain

<httpCookies domain=".xxx.com" httpOnlyCookies="true"/>

SQLServer模式 
http://www.cnblogs.com/haoxue/archive/2010/10/11/asp_net_session_share.html 
http://www.cnblogs.com/whyloverjack/archive/2011/11/10/2244719.html

Custom模式Provider

Redis 
基于Redis的实现 
Harbour.RedisSessionStateStore 
https://github.com/TheCloudlessSky/Harbour.RedisSessionStateStore 
ASP.NET下跨应用共享Session和使用Redis进行Session托管 
http://www.cnblogs.com/UliiAn/p/3554863.html

Microsoft.Web.RedisSessionStateProvider 
https://www.nuget.org/packages/Microsoft.Web.RedisSessionStateProvider

MongoDB 
Custom ASP.NET session state store using MongoDB 
http://www.adathedev.co.uk/2011/05/mongodb-aspnet-session-state-store.html 
https://github.com/AdaTheDev/MongoDB-ASP.NET-Session-State-Store

Memecache 
https://github.com/enyim/memcached-providers 
http://www.cnblogs.com/luminji/archive/2011/11/03/2195704.html

AppFabric 
https://msdn.microsoft.com/zh-cn/library/ee790859.aspx 
http://www.cnblogs.com/xling/archive/2012/07/20/2600439.html

Refer: 
Exploring Session in ASP.NET 
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net 
Announcing ASP.NET Session State Provider for Redis Preview Release 
http://blogs.msdn.com/b/webdev/archive/2014/05/12/announcing-asp-net-session-state-provider-for-redis-preview-release.aspx 
ASP.NET Session State Provider for Azure Redis Cache 
https://msdn.microsoft.com/en-us/library/azure/dn690522.aspx 
在Forms验证模式下,实现多个站点(SubDomain相同)共享同一用户登录状态 
http://www.cnblogs.com/caomao/archive/2005/07/05/186606.html#3013251 
ASP.NET二级域名站点共享Session状态 
http://www.cnblogs.com/jzywh/archive/2008/11/02/ShareSession.html 
Asp.net 多服务器 Session共享 
http://www.cnblogs.com/2814/archive/2012/11/06/2757538.html

posted @ 2015-08-24 11:55  awp110  阅读(1306)  评论(0编辑  收藏  举报