【问题标题】:asp.net cookies stores no dataasp.net cookie 不存储任何数据
【发布时间】:2015-04-30 17:36:27
【问题描述】:

我正在尝试向我的网页添加一个选项,以便在用户登录时拥有“记住我”选项。为了实现这一点,我试图将用户数据(名称+密码)存储在 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);

在我的登录控制器上,我的代码如下所示:

        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 始终为空。我错过了什么?

【问题讨论】:

  • 客户端是否接受cookies?
  • 是的,它接受 cookie

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


【解决方案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);

读取/获取 Cookies

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2013-02-20
    • 2010-12-17
    • 2017-04-30
    相关资源
    最近更新 更多