cookie没有添加

时间:2012-07-10 11:58:28

标签: asp.net .net asp.net-mvc-3 cookies

我在服务器上添加了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);
}

但是当我从Request中读取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;
    }
}

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

3 个答案:

答案 0 :(得分:1)

因此,基本上需要保留两条信息。身份证和失效日期。如何将有效期限存储在单独的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的值。

答案 1 :(得分: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.Security添加汇编FormsAuthenticationTicket

答案 2 :(得分: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 - 如果它们过期,客户端将不会发送它们。