我正在处理 mvc.net 中的自定义登录页面。我像这样检查登录名:
public bool Login(string login, string password, bool persistent)
{
var loginEntity = this.AdminRepository.GetLogin(login, password);
if (loginEntity != null)
{
FormsAuthentication.SetAuthCookie(login, persistent);
HttpContext.Current.Session["AdminId"] = loginEntity.AdminId;
HttpContext.Current.Session["AdminUsername"] = loginEntity.Username;
return true;
}
然后我用过滤器属性装饰任何需要管理员访问权限的控制器:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var ctx = HttpContext.Current;
// check if session is supported
if (ctx.Session != null)
{
var redirectTargetDictionary = new RouteValueDictionary();
// check if a new session id was generated
if (ctx.Session.IsNewSession)
{
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers["Cookie"];
if (((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) || null == sessionCookie)
{
redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("area", "Admin");
redirectTargetDictionary.Add("action", "LogOn");
redirectTargetDictionary.Add("controller", "Home");
filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
}
} else if (SessionContext.AdminId == null) {
redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("area", "Admin");
redirectTargetDictionary.Add("action", "LogOn");
redirectTargetDictionary.Add("controller", "Home");
filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
}
}
base.OnActionExecuting(filterContext);
}
我看到登录后我有两个cookie:
- ASPXAUTH(到期日期设置为“在会话结束时”(当持久为假时)或(从现在起 30 分钟(当持久设置为真)
- 和 ASP.NET_SessionId 过期时间总是“在会话结束时”
问题:问题是即使我将 TRUE 设置为“persists”选项(这将设置 ASPXAUTH 过期时间从现在开始 30 分钟 - 这很好),我的 Session["AdminId"] 在我关闭并重新打开浏览器后始终为空。当我最初将“persists”设置为true并关闭然后重新打开浏览器窗口时,如何确保从cookie中提取我的会话(Session [“AdminId”]和Session [“AdminUsername”])。谢谢