何时应将HttpResponse.SuppressContent设置为true?

7
我写了一个HTTP模块,用于验证URL,如果其中包含特殊符号,我会将其重定向到根目录。
我找到了不同的实现方式,并且有人建议将HttpResponse.SuppressContent属性设置为true。但是我不确定这种情况下会发生什么。MSDN表示它指示是否要向客户端发送HTTP内容,那么这是否意味着重定向不是由客户端发起,而是由服务器发起的?
1个回答

12

默认情况下,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");
    // Exception was thrown by previous statement. These two lines do not run.
    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接