How can I create persistent cookies in ASP.NET?

后端 未结 6 1713
太阳男子
太阳男子 2020-11-27 12:27

I am creating cookies with following lines:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Respons         


        
6条回答
  •  北海茫月
    2020-11-27 13:06

    Although the accepted answer is correct, it does not state why the original code failed to work.

    Bad code from your question:

    HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
    userid.Expires.AddYears(1);
    Response.Cookies.Add(userid);
    

    Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.

    Corrected code:

    HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
    userid.Expires = DateTime.Now.AddYears(1);
    Response.Cookies.Add(userid);
    

提交回复
热议问题