ASP Cookies

写 Cookie、读 Cookie、设置过期与路径、多值 Cookie。

Beginner
Key Points写 Cookie 用 Response.Cookies,读用 Request.Cookies;必须在任何输出之前写。

写 Cookie

ASP
<%
    Response.Cookies("theme") = "dark"
    Response.Cookies("theme").Expires = DateAdd("d", 7, Date())   ' 7 天后过期
    Response.Cookies("theme").Path = "/"
    Response.Cookies("theme").Secure = False
%>
<!DOCTYPE html><html><body><p>主题已保存</p></body></html>

Without Expires it is a session cookie that dies with the browser. Setting it persists to disk. Path defaults to the current directory, so pages elsewhere cannot read it.

读 Cookie

ASP
<%
    Dim theme
    theme = Request.Cookies("theme")
    If theme = "" Then theme = "light"

    Response.Write "当前主题:" & theme
%>
Output
当前主题:dark

A missing cookie yields an empty string rather than an error, so If ... = "" is a safe check — unlike JavaScript's undefined.

多值 Cookie

ASP
<%
    ' 一个 Cookie 里存多个键
    Response.Cookies("user")("name") = "Ada"
    Response.Cookies("user")("role") = "admin"
    Response.Cookies("user").Expires = DateAdd("d", 30, Date())

    ' 读
    Response.Write Request.Cookies("user")("name") & "<br>"
    Response.Write Request.Cookies("user")("role")
%>
Output
Ada
admin

A multi-value cookie is one cookie whose value is name=Ada&role=admin. It saves against the per-domain cookie count but parses slightly slower and still hits the 4KB limit.

删除 Cookie

ASP
<%
    Response.Cookies("theme").Expires = DateAdd("d", -1, Date())
    Response.Cookies("theme").Path = "/"
%>

Deleting means setting an expiry in the past. Path must match the original or the browser treats it as a different cookie and the delete fails — the usual cause of "cannot clear the login state".

Cookies are plain text on the user's machine and freely editable. Never store authorisation like role=admin in a cookie — changing it to role=user escalates privileges. Keep permissions in the session or database.

Cookie 的局限

LimitValue
Size per cookie约 4KB
Cookies per domain约 50 个(浏览器不同)
Sent on every request是,浪费带宽
User editable是

Friends & Partners