閱讀目錄 開始 通過IHttpModule註冊過濾管道方式 通過BaseController 關於滑動過期 兩種方式 回到頂部 通過IHttpModule註冊過濾管道方式 具體實現如下: 聲明一個類CheckLoginModule.cs它繼承自IHttpModule 在請求管道的第9個事件 即獲得用 ...
閱讀目錄
兩種方式 回到頂部通過IHttpModule註冊過濾管道方式
具體實現如下: 聲明一個類CheckLoginModule.cs它繼承自IHttpModule 在請求管道的第9個事件 即獲得用戶狀態的事件中 註冊OnRequest事件 判斷Memcached中是否存在對應客戶端SessionId的用戶信息 不存在則意味服務端Session失效 接著判斷是否具有保留一周的Cookie(通常網站"記住我一周"的功能) 如果存在 根據Cookie信息獲取用戶信息 寫入Memcached中 假設當用戶請求/home/index 頁面時 我們要求用戶必須登錄 即服務端有該用戶信息 不存在則跳轉至/home/login頁面進行登錄操作 CheckLoginModule.cs文件內容如下:using System; using System.Web; using MvcMamcache.Models; namespace MvcMamcache.Common { public class CheckLoginModule : IHttpModule { #region IHttpModule 成員 public void Init(HttpApplication context) { context.AcquireRequestState += new EventHandler(OnRequest); } public void OnRequest(object source, EventArgs e) { HttpApplication application = source as HttpApplication;//得到Application HttpContext context = application.Context;//得到請求上下文. Uri url = context.Request.Url;//得到當前請求的URL if(url.AbsolutePath.ToLower() == "/home/index") { var httpCookie = context.Request.Cookies["SessionId"]; if(httpCookie == null || Common.MemCacheHelper.GetValue(httpCookie.Value) == null) {//Session會話過期 //是否保留7天 if(context.Request.Cookies["ui1"] == null || context.Request.Cookies["ui2"] == null) { context.Response.Redirect("/home/login"); } else { //根據Cookie中保存的用戶名與密碼至資料庫獲取UserInfo對象 這裡直接new UserInfo userInfo = new UserInfo() { LoginId = context.Request.Cookies["ui1"].Value, LoginPwd = context.Request.Cookies["ui2"].Value }; var sessionId = Guid.NewGuid().ToString(); context.Response.Cookies["SessionId"].Value = sessionId; Common.MemCacheHelper.Insert(sessionId, userInfo); } } } } public void Dispose() { throw new NotImplementedException(); } #endregion } }
需要將此過濾Module在Web.Config文件中進行配置
<httpModules> <add name="CheckLoginModule" type="MvcMamcache.Common.CheckLoginModule"/> </httpModules>Home控制器中Index與Login方法的調整 回到頂部
通過BaseController
自定義的父類控制器 它繼承自Controller 在控制器Initialize中 進行校驗 並聲明LoginUserInfo屬性保存用戶信息供所有子Controller使用
using System; using System.Web.Mvc; using MvcMamcache.Models; namespace MvcMamcache.Common { public class BaseController : Controller { protected UserInfo LoginUserInfo { get; set; } protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); if(requestContext.HttpContext.Request.Cookies["SessionId"] != null) { string guid = requestContext.HttpContext.Request.Cookies["SessionId"].Value; object obj = Common.MemCacheHelper.GetValue(guid);//根據Cookie的值從緩存中取出數據. if(obj != null) { UserInfo model = obj as UserInfo; LoginUserInfo = model; } else { CheckCookieSevenDay(requestContext);//7天Cookie檢驗 } } else { Response.Redirect("/home/login"); } } private void CheckCookieSevenDay(System.Web.Routing.RequestContext requestContext) { var context = requestContext.HttpContext; if(context.Request.Cookies["ui1"] == null || context.Request.Cookies["ui2"] == null) { context.Response.Redirect("/home/login"); } else { //根據Cookie中保存的用戶名與密碼至資料庫獲取UserInfo對象 這裡直接new UserInfo userInfo = new UserInfo() { LoginId = context.Request.Cookies["ui1"].Value, LoginPwd = context.Request.Cookies["ui2"].Value }; var sessionId = Guid.NewGuid().ToString(); context.Response.Cookies["SessionId"].Value = sessionId; Common.MemCacheHelper.Insert(sessionId, userInfo); } } } }
需要用戶狀態校驗的控制器中
using System.Web.Mvc; using MvcMamcache.Common; namespace MvcMamcache.Controllers { public class AdminController : BaseController { // // GET: /Admin/ public ActionResult Index() { ViewBag.UserName = LoginUserInfo.LoginId; return View(); } } }回到頂部
關於滑動過期
上述第一種方式中我們通過設置了緩存過期時間為20分鐘 但這是絕對過期時間 而非滑動過期 若想實現滑動過期也好辦 通過Memcached的Replace(key,value,newTimeSpan)來更新失效時間 不在原有代碼上調整,這裡提供思路如下:if(Common.MemCacheHelper.GetValue("GetNow") == null) { Common.MemCacheHelper.Insert("GetNow", DateTime.Now, DateTime.Now.AddMinutes(1)); ViewBag.Msg = "新增時間" + Common.MemCacheHelper.GetValue("GetNow").ToString() + "失效時間應該在:" + ((DateTime)Common.MemCacheHelper.GetValue("GetNow")).AddMinutes(1); } else { Common.MemCacheHelper.Replace("GetNow", DateTime.Now, DateTime.Now.AddMinutes(30)); ViewBag.Msg = "替換時間" + Common.MemCacheHelper.GetValue("GetNow").ToString() + "失效時間應該在:" + ((DateTime)Common.MemCacheHelper.GetValue("GetNow")).AddMinutes(30); }
當然session的替代方案遠不止使用Memcached 還可以通過Nosql非關係型資料庫,話說ManagDB的效率相當稱贊