日期:2014-05-17  浏览次数:20495 次

ASP.NET MVC2 保存Cookie保存不了
C# code
         string data = string.Empty;
                //用户数据转成一个字符串。
                if (model != null)
                    data = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);
                //创建FormsAuthenticationTicket
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserAccount, DateTime.Now, DateTime.Now.AddDays(7), true, data);
                //加密
                string cookieValue = FormsAuthentication.Encrypt(ticket);
                //创建FormsAuthenticationTicket
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
                cookie.HttpOnly = true;
                cookie.Secure = FormsAuthentication.RequireSSL;
                cookie.Domain = FormsAuthentication.CookieDomain;
                cookie.Path = FormsAuthentication.FormsCookiePath;
                cookie.Expires = DateTime.Now.AddDays(7);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                //身份验证
                FormsAuthentication.RedirectFromLoginPage(model.UserAccount, false);



试过很多种很多种方法都无法创建 Cookies,大神求救!!!

------解决方案--------------------
用Response.Cookies添加cookie或者可以用我写的方法
C# code

 public void SignIn(HttpContextBase httpContext, string userName, string userId, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("值不能为 null 或为空。", "userName");
            }

            if (String.IsNullOrEmpty(userId))
            {
                throw new ArgumentException("值不能为 null 或为空。", "roles");
            }

            var ticket = new FormsAuthenticationTicket(
                1,
                userName,
                DateTime.Now,
                DateTime.Now.Add(FormsAuthentication.Timeout),
                createPersistentCookie,
                userId);

            SetAuthCookie(httpContext, ticket);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public void SetAuthCookie(HttpContextBase httpContext, FormsAuthenticationTicket authenticationTicket)
        {
            //DateTime issueDate = DateTime.Now;


            //string protectedTicket = FormsAuthentication.Encrypt(authenticationTicket);

            //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, protectedTicket);
            //cookie.HttpOnly = true;
            //cookie.Expires = issueDate.AddMinutes(20);

            //HttpContext.Current.Response.Cookies.Add(cookie);
            var encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);
            httpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = CalculateCookieExpirationDate() });
        }

------解决方案--------------------
是不是有重名的cookies了,所以你的cookies不能创建成功!