//生成cookie private void SetUserDate(LoginUserDTOModel loginUserDTOModel) { //把用户信息转为json字符串 var userData = loginUserDTOModel.ToJson();//扩展方法自己封装的时候 参数传一个this; // 创建票据FormsAuthenticationTicket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginUser", DateTime.Now, DateTime.Now.AddDays(1), false, userData); // 创建Cookie HttpCookie FormsAuthentication var ticketEncrypt = FormsAuthentication.Encrypt(ticket); //创建Cookie 根据web.config里面的authentication 节点进行cookie 创建 HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypt) { HttpOnly = true, Secure = FormsAuthentication.RequireSSL, Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath, Expires = DateTime.Now.Add(FormsAuthentication.Timeout) }; // 获取http请求上下文 HttpContext context = HttpContext.Current; if (context == null) { throw new ArgumentNullException("context为空"); //抛出异常 } context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); //先remove在写入 context.Response.Cookies.Add(cookie); //写入cookie }
/// <summary> /// 存入票据信息 /// </summary> /// <param name="dtoUserModel"></param> public void SetUserData(LoginUserDTOModel dtoUserModel) { //1、获取用户数据转成json var userData = dtoUserModel.ToJson(); //2、创建票据FormsAuthenticationTicket(对票据进行加密FormsAuthentication.Encrypt)(https://technet.microsoft.com/zh-cn/library/system.web.security.formsauthenticationticket.version) FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginUser", DateTime.Now, DateTime.Now.AddDays(1), false, userData); //加密 var ticketEncrypt = FormsAuthentication.Encrypt(ticket); //3、创建Cookie HttpCookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypt); cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout); cookie.Domain = FormsAuthentication.CookieDomain; cookie.HttpOnly = true; cookie.Secure = FormsAuthentication.RequireSSL; cookie.Path = FormsAuthentication.FormsCookiePath; //4、获取HTTP上下文 HttpContext; HttpContext context = HttpContext.Current; if (context == null) { throw new ArgumentNullException("context为空"); } //5、写入Cookie(https://www.cnblogs.com/tzyy/p/4151291.html) context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); context.Response.Cookies.Add(cookie); }