【问题标题】:Asp.net .ASPXAUTH cookie value always emptyAsp.net .ASPXAUTH cookie 值始终为空
【发布时间】:2017-12-20 13:53:21
【问题描述】:

这里我有一段代码用 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");
}

【问题讨论】:

标签: c# asp.net cookies


【解决方案1】:

尝试用您的 Encrypt 方法替换此代码

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 个参数传递。

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多