(1)、用户登录成功之后将信息写入Cookie和memcached服务器,
关键代码:
//用户登录成功
var userInfo = UserInfoService.GetEntities(u => u.UName == userName && u.Pwd == userPwd).FirstOrDefault();
if (userInfo != null)
{
//模拟的SessionId
string usersLoginId = Guid.NewGuid().ToString();
//将用户信息写入memcache,模拟SessionId
memcachedHelper.set(usersLoginId, SerializerHelper.SerializerToString(userInfo), DateTime.Now.AddMinutes(20));
//将模拟的SessionId写入客户端Cookie中
Response.Cookies["usersLoginId"].Value = usersLoginId;
}
(2)、在基类控制器中的OnActionExecuting方法进行判断是否用户信息是否存在,是否可以访问接下来的页面
关键代码:
public class BaseController : Controller
{
public UserInfo userInfo { get; set; }
private bool isExp = false;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
//Action执行之前判断memcache是否有值(用户是否已经登录)
if (Request.Cookies["usersLoginId"] != null)
{
string usersLoginId = Request.Cookies["usersLoginId"].Value;
object obj = memcachedHelper.Get(usersLoginId);
if (obj != null)
{
userInfo = SerializerHelper.DeSerializerToObject<UserInfo>(obj.ToString());//反序列化
//模拟Session的滑动过期时间
memcachedHelper.Update(usersLoginId, obj, DateTime.Now.AddMinutes(20));
isExp = true;
}
else
{
filterContext.Result = new RedirectResult("登陆界面");
return;
}
}
else
{
filterContext.Result = new RedirectResult("登陆界面");
return;
}
if (!isExp)
{
RedirectToAct.RedirectTo();
return;
}
}
}
(3)、获取用户信息
关键代码:
string usersLoginId = Request.Cookies["usersLoginId"].Value;
object obj = memcachedHelper.Get(usersLoginId);
UserInfo userInfo = SerializerHelper.DeSerializerToObject<UserInfo>(obj.ToString());//反序列化