asp.net将用户名保存为cookie,然后自动填充

时间:2013-01-21 20:39:07

标签: asp.net cookies login username

我正在尝试将用户输入的内容保存到用户名文本框中作为cookie,然后在后续访问中使用登录表单自动填充带有cookie值的文本框。我做错了什么?

这会将用户名保存为cookie值,但在返回登录页面时,cookie值似乎返回null。

我目前有:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim UserName As TextBox = DirectCast(LoginUser.FindControl("UserName"), TextBox)
    If User.Identity.IsAuthenticated Then
        Response.Redirect("~/media")
    End If
    Dim UserNameCookie As New HttpCookie("User_Name")
    UserNameCookie.Secure = True
    UserNameCookie.HttpOnly = True
    UserNameCookie.Expires = DateTime.Today.AddDays(7)
    UserNameCookie.Value = UserName.Text
    Response.Cookies.Add(UserNameCookie)

    If Request.Cookies("UserName") IsNot Nothing Then
        UserName.Text = Request.Cookies("UserName").Value.ToString()
    End If

End Sub

1 个答案:

答案 0 :(得分:2)

将用户名更改为User_Name。 Cookie名称必须相同。

If Request.Cookies("User_Name") IsNot Nothing Then
   UserName.Text = Request.Cookies("User_Name").Value.ToString()
End If