Cookies not saved between browser sessions on iOS Safari

后端 未结 2 1301
庸人自扰
庸人自扰 2021-01-04 05:53

I have an MVC 4 website where a user can login and I save a cookie with their session information so they don\'t have to login again.

public void SetCookie(H         


        
2条回答
  •  借酒劲吻你
    2021-01-04 06:16

    I think you answered your own question with persistent cookie. Regular cookies expire when the browser session ends (this is typically closing the browser). Persistent cookies have a date when they should be removed and can live across browser sessions.

    Your code should look something like this:

    private HttpCookie CreateAuthenticationCookie(int loginId, string username)
    {
        string userData = string.Format("loginId:{0},username:{1}", loginId, username);
        var ticket = new FormsAuthenticationTicket(loginId, username, 
                             DateTime.Now, DateTime.Now.AddYears(1), 
                             false, userData, FormsAuthentication.FormsCookiePath);
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);
    
        return new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket){{
             Expires = DateTime.Now.AddYears(1);
        }};
    }
    

    This way your cookie will persist across browser sessions for one year.

提交回复
热议问题