How can I create persistent cookies in ASP.NET?

后端 未结 6 1736
太阳男子
太阳男子 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 12:58

    As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.

    bool isPersisted = true;
    var authTicket = new FormsAuthenticationTicket(
    1,
    user_name, 
    DateTime.Now,
    DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
    isPersisted,//THIS IS THE MAIN FLAG
    addition_data);
        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
        if (isPersisted)
            authCookie.Expires = authTicket.Expiration;
    
    HttpContext.Current.Response.Cookies.Add(authCookie);
    

提交回复
热议问题