【问题标题】:SetPrincipal (@User.Identity.Name) from a cookie in ASP.Net MVCSetPrincipal (@User.Identity.Name) 来自 ASP.Net MVC 中的 cookie
【发布时间】:2015-02-20 15:27:42
【问题描述】:

我想知道当用户点击记住我复选框时,如何通过 cookie 设置 @User.Identity.Name

Cookie 代码

if (_model.RememberMe)
{
    HttpCookie cookie = new HttpCookie("login");
    cookie.Values.Add("username", _model.Username);
    cookie.Expires = DateTime.Now.AddDays(30);
    Response.Cookies.Add(cookie);
}

首次登录代码

if (Membership.ValidateUser(Username,Password))
{
    RememberMe();

    FormsAuthentication.RedirectFromLoginPage(Username, false);
}

在第一次登录时设置了 Identity.name,但是当我关闭浏览器并返回该站点时。它无需用户输入凭据即可正确登录,但Identity.name 为空。

if (Request.Cookies["login"] != null)
{
     // We know the automatic log in has worked as it comes into here...
}

用户通过登录页面后,我需要做什么才能设置iPrincipal 对象?

谢谢

【问题讨论】:

  • 不能直接设置User.Identity.Name,需要创建FormsAuthenticationTicket msdn.microsoft.com/en-us/library/…
  • 哇,就是这么简单。谢谢你一整天都在做我。让它成为一个答案,如果你喜欢它会标记它

标签: c# asp.net-mvc cookies forms-authentication


【解决方案1】:

请尝试以下代码 注意:请在页面视图中检查,与创建 cokies 的方法不同

private void CreateCokies(string userName)
    {
        var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), true, userName);
        string cookieContents = FormsAuthentication.Encrypt(authTicket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
        {
            Expires = authTicket.Expiration,
            Path = FormsAuthentication.FormsCookiePath
        };
        Response.Cookies.Add(cookie);
    }

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2012-01-17
    • 2019-02-07
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多