【问题标题】:ASP.NET - Why is my cookie not persisted?ASP.NET - 为什么我的 cookie 没有持久化?
【发布时间】:2012-08-09 17:21:21
【问题描述】:

我正在尝试设置一个 cookie 来存储选定的部门。该 cookie 设置为一个带有部门选择下拉列表的小表单。这是使用 AJAX 发布的。

这就是我存储 cookie 的方式:

<AcceptVerbs(HttpVerbs.Post)> _
Function ChangeDepartment(ByVal FormValues As FormCollection) As ActionResult
    If Response.Cookies("department") IsNot Nothing Then
        Response.Cookies("department").Value = FormValues("department")
    Else
        Dim c As New HttpCookie("department")
        c.Value = FormValues("department")
        c.Expires = Now.AddDays(7)
        Response.Cookies.Add(c)
    End If

    Return Json(New With {.newDepartment = Response.Cookies("department").Value})
End Function

.newDepartment 变量以正确的值正确返回。

这就是我检索 cookie 并构建 select-dropdown 的方式:

<% Ajax.BeginRouteForm("ChangeDepartment", New AjaxOptions With {.LoadingElementId = "loading", .HttpMethod = "post", .OnSuccess = "function(request) {ajaxMessage('Department change', 'Department changed to: ' + request.get_response().get_object().newDepartment);}"})%>
    <select name="department">
        <option>Default</option>
        <option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Supervisor" Then Response.Write (" selected=""selected""") %>>Supervisor</option>
        <option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Purchasing" Then Response.Write (" selected=""selected""") %>>Purchasing</option>
        <option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Engineering" Then Response.Write (" selected=""selected""") %>>Engineering</option>
    </select>
    <input type="submit" value="Change department" />
<% Html.EndForm%>

没有存储 cookie,因为选择下拉菜单一直返回到 Default。难道我做错了什么?

【问题讨论】:

    标签: asp.net-mvc cookies


    【解决方案1】:

    您可以尝试使用 http 调试器,例如用于 IE 的 Fiddler 和用于 FireFox 的 HttpFox。 检查 cookie 是否真的与服务器响应一起发送,以及浏览器是否将其与进一步的请求一起发送回来。 从那里您可能会跟踪问题并查看问题所在。如果您仍然有问题,您可以在此处发布 http 流量。

    【讨论】:

    • 好的,这给了我更多信息。事实证明,我正在清除获得值的 cookie 值。但不知何故,过期值总是会话结束。 Response.Cookies("department").expires = Now.AddDays(7) 好像打不通?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多