简体   繁体   中英

Cookie Doesn't want to expire ASP.NET

I'm having a cookie which I set using java script then I try to make it expired after using it using ASP.NET I checked the cookie using firefox it showed that it's expiry date is set to session although I set the expiry date as you may see below I tried deleting the cookies with no use they still get created with the same state and don't seen to want to get expired

java script

      function dateSelected(sender, eventArg) {
        var expire = new Date();
        expire.setDate(expire.getTime() + (5 * 24 * 60 * 60 * 1000));
        var element = sender._clientStateFieldID;
        if (element == "txtenddate_ClientState")
            document.cookie = "EndDate=" + eventArg.get_newValue() + ";expires=" + expire.toUTCString() + ";path=/";
        else
            document.cookie = "StartDate=" + eventArg.get_newValue() + ";expires=" + expire.toUTCString() + ";path=/";
    }

ASP.NET C#

 StringBuilder url = new StringBuilder();
 url.Append("&StartDate=");
 url.Append(Request.Cookies["StartDate"].Value);
 url.Append("&EndDate=");
 url.Append(Request.Cookies["EndDate"].Value);
 Request.Cookies["StartDate"].Expires = DateTime.Now.AddDays(-1d);
 Request.Cookies["EndDate"].Expires = DateTime.Now.AddDays(-1d);
 Request.Cookies.Add(Request.Cookies["EndDate"]);
 Request.Cookies.Add(Request.Cookies["StartDate"]);
 Server.Transfer(url.ToString());

Although I doesn't explain why the cookie expiry date was set to session although I explicitly set it to a specific date the actual problem was solved by adjusting the two add lines to use the Response instead of the Request collection just like Andrew suggested

 Response.Cookies.Add(Request.Cookies["EndDate"]);
 Response.Cookies.Add(Request.Cookies["StartDate"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM