Asp.net .ASPXAUTH cookie值始终为空

时间:2017-12-19 10:57:20

标签: c# asp.net cookies

这里我有一段代码用asp.net FormAuthenticationTicket制作一个cookie。当我调试代码时,我发现故障单的截止日期是正确的,但cookie的截止日期更改为01/01/0001/12:00:000AM。知道为什么会这样吗? 此外,在浏览器中,cookie的名称是.ASPXAUTH,但值为空。因此,每当我们浏览网页时,我们就会被踢出去。

身份验证类

public class TicketAuth
{
    public HttpCookie Encrypt(string id)
    { 
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, id, DateTime.Now, DateTime.Now.AddHours(3), false, "", FormsAuthentication.FormsCookiePath);
        HttpCookie c = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
        return c;
    }

    public int Decrypt()
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
        int key = Convert.ToInt32(ticket.Name);
        return key;
    }
}

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Account account)
{
    TicketAuth ticket = new TicketAuth();
    HttpCookie c = ticket.Encrypt(account.Id.ToString());
    HttpContext.Response.Cookies.Add(c);
    if (account.Admin)
    {
        return RedirectToAction("Accounts");
    }
    return RedirectToAction("Bon", "Bon");
}

1 个答案:

答案 0 :(得分:0)

尝试使用您的加密方法替换此代码

public HttpCookie Encrypt(string id)
{ 
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "someName", DateTime.Now, DateTime.Now.AddHours(3), false, id, FormsAuthentication.FormsCookiePath);
    HttpCookie c = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
    return c;
}

您需要将序列化对象作为FormsAuthenticationTicket构造函数中的第6个参数传递。