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.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 何が問題なのかわかりません。

4

3 に答える 3

1

したがって、基本的に2つの情報を保持する必要があります。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の有効期限を確認するには、wmpaymentCookieの値を読み取ります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.Securityを追加しますFormsAuthenticationTicket

于 2012-07-10T13:45:46.690 に答える
0

Cookie がサーバーに送信されると、「Expires」オプションが含まれていないため、exp設定されず、デフォルト値の DateTIme.MinValue が保持されます。そのため、DateTime.Now < expは true になら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 に答える