asp.net cookies不存储任何数据

时间:2015-04-30 08:52:31

标签: c# asp.net-mvc-4 cookies

我正在尝试在我的网页上添加一个选项,这样当用户登录时就会记住我'选项。为了实现这一点,我试图将用户数据(名称+密码)存储在cookie中,但它目前无法正常工作。 我存储cookie的代码是:

                int timeout = 525600; 
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.UserName, true, timeout);
                string encrypted = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                FormsAuthentication.SetAuthCookie(model.UserName, true);
                Request.Cookies.Add(cookie);

在我的logIn控制器上,我的代码如下:

        HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
        if (cookie != null)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            var userName = ticket.UserData;
        }

问题是userData cookie始终为空。我错过了什么?

1 个答案:

答案 0 :(得分:1)

试试这个。

  

创建/编写Cookie

方式1

`HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);`

方式2

    Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

方式3

Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
  

阅读/获取Cookie

string roll = Request.Cookies["StudentCookies"].Value;
  

删除Cookie

 if (Request.Cookies["StudentCookies"] != null)
{
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
    Response.Redirect("Result.aspx");  //to refresh the page
}

参考here