Memcache + Cookie alternative Session solution (MVC version), memcachemvc
Reading directory
- Start
- Use IHttpModule to register and filter MPs queues
- Use BaseController
- About sliding expiration
The two methods return to the top and use IHttpModule to register and filter pipelines. The specific implementation is as follows: declare a CheckLoginModule class. cs inherits from IHttpModule and registers the OnRequest event in the 9th events in the request pipeline, that is, events that obtain the user status. If the user information of the corresponding client SessionId does not exist in Memcached, the server Session becomes invalid. determine whether a Cookie is retained for one week (usually the website "Remember me for one week" function) if the user information obtained based on the Cookie information is written into Memcached, assume that when the user requests the/home/index page, the user must log on. That is, if the user information on the server does not exist, the user will jump to/home/login. page to log on to the CheckLoginModule. the cs file is as follows:
Using System; using System. web; using MvcMamcache. models; namespace MvcMamcache. common {public class CheckLoginModule: IHttpModule {# region IHttpModule member public void Init (HttpApplication context) {context. acquireRequestState + = new EventHandler (OnRequest);} public void OnRequest (object source, EventArgs e) {HttpApplication application = source as HttpApplication; // obtain Application HttpContext context = application. context; // obtain the request Context. uri url = context. request. url; // obtain the URL if (url. absolutePath. toLower () = "/home/index") {var httpCookie = context. request. cookies ["SessionId"]; if (httpCookie = null | Common. memCacheHelper. getValue (httpCookie. value) = null) {// Session expiration // whether to retain 7 days if (context. request. cookies ["ui1"] = null | context. request. cookies ["ui2"] = null) {context. response. redirect ("/home/login");} else {// obtain the UserInfo object from the database based on the user name and password saved in the Cookie. Here, new UserInfo userInfo = new UserInfo () is used directly () {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 }}
You need to configure the filter Module in the Web. Config file.
The Index and Login methods in the Home controller are adjusted back to the top using BaseController
The custom parent class Controller inherits from the Controller for verification in the Controller Initialize and declares the LoginUserInfo attribute to save user information for all sub-controllers.
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); // retrieves data from the cache based on the Cookie value. if (obj! = Null) {UserInfo model = obj as UserInfo; LoginUserInfo = model;} else {CheckCookieSevenDay (requestContext); // 7-day Cookie check} 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 {// obtain the UserInfo object from the database based on the user name and password saved in the Cookie. Here, new UserInfo userInfo = new UserInfo () is used directly () {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 );}}}}
In the Controller that requires user status verification
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(); } }}
Back to the top about sliding expiration in the first method above we set the cache expiration time to 20 minutes, but this is the absolute expiration time rather than the sliding expiration time to achieve sliding expiration or through Memcached Replace (key, value, newTimeSpan) to update the expiration time is not adjusted in the original code. Here we provide the following ideas:
If (Common. memCacheHelper. getValue ("GetNow") = null) {Common. memCacheHelper. insert ("GetNow", DateTime. now, DateTime. now. addMinutes (1); ViewBag. msg = "New Time" + Common. memCacheHelper. getValue ("GetNow "). toString () + "the expiration time should be:" + (DateTime) Common. memCacheHelper. getValue ("GetNow ")). addMinutes (1);} else {Common. memCacheHelper. replace ("GetNow", DateTime. now, DateTime. now. addMinutes (30); ViewBag. msg = "replacement time" + Common. memCacheHelper. getValue ("GetNow "). toString () + "the expiration time should be:" + (DateTime) Common. memCacheHelper. getValue ("GetNow ")). addMinutes (30 );}
Of course, the alternative solution of session is far from using Memcached but also using Nosql non-relational databases. The efficiency of ManagDB is quite commendable.
Click to download resources