首页 > 解决方案 > 经典 Asp cookie 过期日期并不总是设置

问题描述

我正在尝试在 Classic Asp 中使用 addheader 方法设置 cookie,这是将 HttpOnly 和 Secure 标志添加到 cookie 中的唯一方法。所有代码都可以使用以下代码 - 但有一个例外,它是到期日期/时间。

<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & dateAdd("d", 365, Now()) & ";samesite=Strict;HostOnly"
%>

但是,这似乎是与浏览器相关的问题。在 Firefox 中,我可以在开发人员工具的“存储”选项卡中看到设置了过期时间。但在 Chrome 中,它始终保持默认设置,即会话结束时到期。Edge 也存在同样的问题。

有没有人有这个问题的经验?

标签: vbscriptasp-classic

解决方案


此处记录了预期的日期格式。您需要以这种方式生成到期日期。

在 Classic ASP 中,您可以使用服务器端 JavaScript 轻松生成此类日期。

<!--#include file="HTTPDate.asp"-->
<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & HTTPDate(DateAdd("d", 365, Now())) & ";samesite=Strict;HostOnly"
%>

HTTP日期.asp

<script language="javascript" runat="server">
function HTTPDate(vbsDate){
    return (new Date(vbsDate)).toGMTString().replace(/UTC/, "GMT");
}
</script>

编辑:添加了纯 VBScript 解决方案。

<%
Function CurrentTZO()
    With CreateObject("WScript.Shell") 
        CurrentTZO = .RegRead( _ 
        "HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
    End With
End Function

Function Pad(text)
    Pad = Right("00" & text, 2)
End Function

Function HTTPDate(ByVal localDate)
    localDate = DateAdd("n", CurrentTZO(), localDate)

    ' WeekdayName and MonthName functions relies on locale
    ' need to produce day and month name abbreviations in en-US locale
    Dim locale : locale = SetLocale("en-US")

    Dim out(5)
    out(0) = WeekdayName(Weekday(localDate), True) & ","
    out(1) = Pad(Day(localDate))
    out(2) = MonthName(Month(localDate), True)
    out(3) = Year(localDate)
    out(4) = Join(Array(Pad(Hour(localDate)), Pad(Minute(localDate)), Pad(Second(localDate))), ":")
    out(5) = "GMT"

    SetLocale locale ' set original locale back 

    HTTPDate = Join(out, " ")
End Function

Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & HTTPDate(DateAdd("d", 365, Now())) & ";samesite=Strict;HostOnly"
%>

推荐阅读