Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将用户名值保存到cookie中,以便在用户希望被记住时检索它?_C#_Authentication_Cookies - Fatal编程技术网

C# 如何将用户名值保存到cookie中,以便在用户希望被记住时检索它?

C# 如何将用户名值保存到cookie中,以便在用户希望被记住时检索它?,c#,authentication,cookies,C#,Authentication,Cookies,我正在尝试使用cookies为登录页面中的用户名实现“记住我” 我正在尝试使用值来执行此操作。在cookie对象上添加: ck.Values.Add("username", txtUName.Value); 但是,当我以这种方式添加值时,身份验证会中断。(如果删除该行,身份验证将再次工作。) 如何在不破坏cookie的情况下将用户名保存在cookie中 此位的完整代码为: bool IsRemember = chkPersistCookie.Checked;

我正在尝试使用cookies为登录页面中的用户名实现“记住我”

我正在尝试使用值来执行此操作。在cookie对象上添加:

 ck.Values.Add("username", txtUName.Value);
但是,当我以这种方式添加值时,身份验证会中断。(如果删除该行,身份验证将再次工作。)

如何在不破坏cookie的情况下将用户名保存在cookie中

此位的完整代码为:

            bool IsRemember = chkPersistCookie.Checked;

            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;

            tkt = new FormsAuthenticationTicket(1, txtUName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), IsRemember, "your custom data");

            cookiestr = FormsAuthentication.Encrypt(tkt);

            ck = new HttpCookie("MYCOOKIEAPP", cookiestr);

            if (IsRemember)
            {
                ck.Expires = tkt.Expiration;
                ck.Values.Add("username", txtUName.Value);
            }
            else
            {
                ck.Values.Add("username", txtUName.Value);
                ck.Expires = DateTime.Now.AddMinutes(5);

            }

            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

我设法直接从FormsAuthenticationTicket获得了我需要的东西:

  if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value); 


               txtUName.Value = ticket.Name;
            }
试着使用这个例子,读他们写的东西。我在我的测试项目中对它进行了测试,它很有效

protected void Page_Load(object sender, EventArgs e)
{
    if(Request.Cookies["BackgroundColor"] != null)
    {
        ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
        BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
    }
}

protected void ColorSelector_IndexChanged(object sender, EventArgs e)
{
    BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
    HttpCookie cookie = new HttpCookie("BackgroundColor");
    cookie.Value = ColorSelector.SelectedValue;
    cookie.Expires = DateTime.Now.AddHours(1);
    Response.SetCookie(cookie);
}

请更改问题标题,似乎不是实际问题!