.NET MVC 5:请求之间丢失cookie

时间:2019-02-17 19:58:43

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

我已经实现了自定义身份验证,但是成功登录后无法检索auth cookie。

设置cookie:

HttpContext.Current.User = user;
Thread.CurrentPrincipal = user;
string userData = JsonConvert.SerializeObject(user);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.Handle, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
HttpContext.Current.Response.Cookies.Add(faCookie);

获取Cookie:

HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    user = JsonConvert.DeserializeObject<User>(authTicket.UserData);
}

问题在于HttpContext.Current.Request.Cookies不包含FormsAuthentication.FormsCookieName键,而authTicket始终为空。

1 个答案:

答案 0 :(得分:0)

您的cookie可能立即过期。请通过editthiscookie插件检查您的过期时间。您可以通过此功能使用set cookie。

 public static bool SetCookie(string cookieName, object value, int expires)
    {
        try
        {
            HttpCookie cookie_clc = new HttpCookie(cookieName, value.ToString());
            cookie_clc.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.Cookies.Add(cookie_clc);
            return true;
        }
        catch (Exception)
        {
            return false;
        }

    }