How can I create persistent cookies in ASP.NET?

后端 未结 6 1770
太阳男子
太阳男子 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:02

    Here's how you can do that.

    Writing the persistent cookie.

    //create a cookie
    HttpCookie myCookie = new HttpCookie("myCookie");
    
    //Add key-values in the cookie
    myCookie.Values.Add("userid", objUser.id.ToString());
    
    //set cookie expiry date-time. Made it to last for next 12 hours.
    myCookie.Expires = DateTime.Now.AddHours(12);
    
    //Most important, write the cookie to client.
    Response.Cookies.Add(myCookie);
    

    Reading the persistent cookie.

    //Assuming user comes back after several hours. several < 12.
    //Read the cookie from Request.
    HttpCookie myCookie = Request.Cookies["myCookie"];
    if (myCookie == null)
    {
        //No cookie found or cookie expired.
        //Handle the situation here, Redirect the user or simply return;
    }
    
    //ok - cookie is found.
    //Gracefully check if the cookie has the key-value as expected.
    if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
    {
        string userId = myCookie.Values["userid"].ToString();
        //Yes userId is found. Mission accomplished.
    }
    

提交回复
热议问题