ASP Response

Response 的 Write / Redirect / End / Buffer / ContentType / Cookies 等成员。

Intermediate
Key PointsResponse 负责一切输出:写内容、设头、重定向、提前结束;所有头操作都必须在输出之前。

常用成员

MemberPurpose
Write输出字符串到响应体
BinaryWrite输出图片、文件
Redirect302 跳转
End立即停止执行并输出缓冲区
Flush把缓冲区发给浏览器
BufferTrue 时先缓存再发
ContentTypetext/html、application/json
CharsetUTF-8
Status404 Not Found
AddHeader自定义响应头
Cookies写 Cookie
CacheControlno-cache 禁缓存

Write 与输出

ASP
<%
    Response.Write "第一行<br>"
    Response.Write "第二行<br>"
    Response.Write "拼接:" & (1 + 2) & "<br>"
%>
Output
第一行
第二行
拼接:3

Redirect

ASP
<%
    If Session("uid") = "" Then
        Response.Redirect "login.asp"
    End If
%>

Redirect ends the page immediately (it calls End internally). If output already went out with Buffer = False, headers are on the wire and the redirect fails with "HTTP headers already sent".

Buffer 与 End

ASP
<% Response.Buffer = True %>
<%
    ' 先判断,再决定要不要输出
    If Request("id") = "" Then
        Response.Status = "400 Bad Request"
        Response.Write "缺少 id"
        Response.End
    End If

    ' 正常输出
    Response.Write "处理 id=" & Request("id")
%>

With Buffer = True output collects in a buffer until the page ends or Flush is called, which makes "output then decide to redirect" possible — the buffer can be discarded.

Response.Buffer must be set before any output, including HTML and blank lines. That is why it goes on the first line as a directive attribute; setting it mid-page has no effect.

输出 JSON

ASP
<%
    Response.ContentType = "application/json"
    Response.Charset = "UTF-8"
    Response.Write "{""ok"":true,""name"":""" & Server.HTMLEncode(Request("name")) & """}"
%>
Output
{"ok":true,"name":"Ada"}

VBScript escapes quotes by doubling them, so hand-built JSON becomes a thicket of "". For anything non-trivial write a JsonEncode helper or use a JSON library.

缓存控制

ASP
<%
    Response.CacheControl = "no-cache"
    Response.Expires = -1
    Response.AddHeader "Pragma", "no-cache"
%>

Pages with personal data must disable caching, or pressing Back after logout reveals the previous user's content — a classic privacy incident.

文件下载

ASP
<%
    Dim fname
    fname = "report.csv"
    Response.ContentType = "application/octet-stream"
    Response.AddHeader "Content-Disposition", "attachment; filename=" & fname

    Dim stream
    Set stream = Server.CreateObject("ADODB.Stream")
    stream.Type = 1                                  ' 二进制
    stream.Open
    stream.LoadFromFile Server.MapPath("/data/" & fname)

    Response.BinaryWrite stream.Read
    stream.Close
    Set stream = Nothing
    Response.End
%>

A download page must emit nothing extra: tags, blank lines and BOMs all corrupt the file. The page does exactly one thing — write bytes.

Friends & Partners