默认情况下,ASP.Net会缓冲处理程序的输出。Response.SupressContent可以阻止将该内容发送到客户端,但标题仍将被发送。
示例1 - 带缓冲和SupressContent=false的输出
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("No Supression");
}
</script>
Dynamic Content
<%= DateTime.Now %>
原始Http响应:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Date: Sun, 03 May 2015 23:29:17 GMT
Content-Length: 44
No Supression
Dynamic Content
5/3/2015 5:29:17 PM
示例 2 - 带缓冲和SupressContent=true的输出
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Suppress it all!");
Response.SuppressContent = true;
}
</script>
Dynamic Content
<%= DateTime.Now %>
原始Http响应:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html
Date: Sun, 03 May 2015 23:34:13 GMT
Content-Length: 0
请注意此输出没有内容。
您的问题特别涉及重定向后会发生什么。
示例3-当SupressContent=true时进行重定向。
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("~/SomewhereElse.aspx");
Response.Write("Redirect Supress Content");
Response.SuppressContent = true;
}
</script>
Dynamic Content
<%= DateTime.Now %>
原始的Http响应:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: /SomewhereElse.aspx
Date: Sun, 03 May 2015 23:35:40 GMT
Content-Length: 136
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/SomewhereElse.aspx">here</a>.</h2>
</body></html>
请注意仍有主体存在的原因。那是因为我们没有允许请求完全处理。默认情况下,Response.Redirect会抛出异常,而Response.SupressContent属性未设置为true。如果我们向第二个参数传递false,则看起来像上面的示例。
示例4- 当SupressContent=true时重定向,而Response.Redirect不会抛出异常。
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("~/SomewhereElse.aspx", false);
Response.Write("Redirect Supress Content");
Response.SuppressContent = true;
}
</script>
Dynamic Content
<%= DateTime.Now %>
原始HTTP响应:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html
Location: /SomewhereElse.aspx
Date: Sun, 03 May 2015 23:37:45 GMT
Content-Length: 0