How can I create persistent cookies in ASP.NET?

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

    You need to add this as the last line...

    HttpContext.Current.Response.Cookies.Add(userid);
    

    When you need to read the value of the cookie, you'd use a method similar to this:

        string cookieUserID= String.Empty;
    
        try
        {
            if (HttpContext.Current.Request.Cookies["userid"] != null)
            {
                cookieUserID = HttpContext.Current.Request.Cookies["userid"];
            }
        }
        catch (Exception ex)
        {
           //handle error
        }
    
        return cookieUserID;
    

提交回复
热议问题