0

我在服务器上添加 cookie:

private void AddCookie(int id)
{
    HttpCookie cookie = new HttpCookie("wmpayment");
    cookie.Value = id.ToString();
    cookie.Expires = DateTime.Now.AddDays(2);
    this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
}

但是当我从请求中读取 cookie - cookie.Expire 等于日期 01.01.0001

public static int WMPendingOrder
{
    get
    {
        var cookie = HttpContext.Current.Request.Cookies["wmpayment"];
        int id = 0;
        DateTime exp;

        if (cookie != null)
        {
            DateTime.TryParse(cookie.Expires.ToString(), out exp);
            if (DateTime.Now < exp)
                int.TryParse(cookie.Value, out id);
        }
        return id;
    }
}

日志:COOKIE.Name:wmpayment COOKIE.Value:0 COOKIE.Expire:01.01.0001 0:00:00 我不明白是什么问题。

4

3 回答 3

1

所以基本上有两条信息需要你坚持。id 和到期日期。如何将到期日期存储在单独的 cookie 中:

private void AddCookie(int id) 
{ 
    HttpCookie cookie = new HttpCookie("wmpayment"); 
    cookie.Value = id.ToString(); 
    cookie.Expires = DateTime.Now.AddDays(2); 
    this.ControllerContext.HttpContext.Response.Cookies.Add(cookie); 

    HttpCookie cookie = new HttpCookie("wmpaymentexpire"); 
    cookie.Value = DateTime.Now.AddDays(2).ToString(); 
    cookie.Expires = DateTime.Now.AddDays(2); 
    this.ControllerContext.HttpContext.Response.Cookies.Add(cookie); 
}

因此,要检查 cookie 的过期日期,wmpayment您需要读取 cookie 的值wmpaymentexpire

于 2012-07-10T13:24:19.987 回答
1

您可以使用此代码创建 cookie:

            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;

            tkt = new FormsAuthenticationTicket(1, UsrNm, DateTime.Now,
      DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "Issue Ticket");
            cookiestr = FormsAuthentication.Encrypt(tkt);

            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            if (chkPersistCookie.Checked)
                ck.Expires = tkt.Expiration;
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

            string strRedirect;
            strRedirect = Request["ReturnUrl"];
            if (strRedirect == null)
                strRedirect = "~/default.aspx";
            Response.Redirect(strRedirect, true);

*注意: *添加程序using System.Web.SecurityFormsAuthenticationTicket

于 2012-07-10T13:45:46.690 回答
0

当 cookie 被提交回服务器时,它们不包含“Expires”选项,因此exp不会被填充,因此它保持其默认值 DateTIme.MinValue。因此,DateTime.Now < exp永远不会是真的,所以int.TryParse(cookie.Value, out id)永远不会运行,所以 id 保持它的默认值,0.

试试这个:

public static int WMPendingOrder
{
    get
    {
        var cookie = HttpContext.Current.Request.Cookies["wmpayment"];
        int id = 0;

        if (cookie != null)
        {
            int.TryParse(cookie.Value, out id);
        }
        return id;
    }
}

您不需要在服务器端检查过期的 cookie - 如果它们过期,客户端将不会发送它们。

于 2012-07-10T12:24:52.783 回答