【问题标题】:Session becomes null after browser is closed浏览器关闭后会话变为空
【发布时间】:2013-02-22 00:07:37
【问题描述】:

我使用以下代码跨页面检索登录用户身份

// login method of account model
public ActionResult Login(LoginModel model)
{
    Session["username"]=model.Username;
    //redirect to login controler
}

在登录控制器中

public ActionResult LoginLayout()
{
    if(IsAdmin(Session["username"]))
        return View();
    else
        return OtherView();
}

一切都很好,直到我关闭浏览器然后重新打开它,然后我总是被重定向到OtherView(),即使我仍然被认证为登录用户。

更新

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {                
            Session["username"] = model.UserName;
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

【问题讨论】:

  • 是什么让你说你“仍然经过身份验证”?
  • 我的意思是我仍然以登录用户身份登录
  • 进一步扩展 Floris 的问题,您是否选择了在 Session 之后仍然存在的身份验证方法(如 cookie)?如果是这样,请具体说明并包含代码。
  • 你怎么知道? “仍然登录”是什么意思?通常,当您关闭浏览器时,您会自动退出 - 这里有什么不同?
  • @DaveA 是的,Websecurity 的登录方法我使用持久性 cookie,并且我还选择了 Firefox 提供的记住我

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

您必须始终准备好清除会话状态。例如,如果更改了 web.config 文件,工作进程将被回收,所有进程内会话状态都将丢失。您可以通过使用进程外会话状态来缓解这种情况,但作为最佳实践,您应该随时准备丢失会话。

【讨论】:

    【解决方案2】:

    您只需要检查您是否已登录,因为您的 cookie 是持久化的。它与会话无关,因为关闭浏览器后会话将永远不存在,除非您将会话存储在数据库或状态中

    【讨论】:

      【解决方案3】:

      由于先前的回复状态,您无法在浏览器关闭后回复会话状态仍然有效。 以下两篇文章应该会有所帮助

      ASP.NET Session State Overview

      ASP.NET State Management Recommendations

      提姆

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 2020-07-15
        • 2014-08-15
        • 2011-12-17
        • 2012-04-11
        相关资源
        最近更新 更多