为什么我们使用Response.ClearHeaders()?

时间:2011-07-06 07:20:35

标签: c# asp.net download httpresponse

我复制了一个代码片段以将文件发送到浏览器。我不知道为什么我们使用下面写的行,因为删除它们对我的开发环境没有任何影响。

Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;

任何人都可以简单地分解预期目的吗?适合这些。

由于

3 个答案:

答案 0 :(得分:10)

  

Response.Clear();

如果您已经将任何内容写入缓冲区,则需要清除该内容,因此不会包含任何外来内容。

  

Response.ClearHeaders();

例如,如果先前已指定了内容类型,则您可能不希望这样。可能已经设置了任意数量的HTTP标头 - 缓存控制是另一个很好的例子。

  

Response.Buffer = false;

如果您已准备好将文件转储出来,则无法缓冲输出...只需发送它并且不要浪费内存。

答案 1 :(得分:2)

Response.ClearHeaders确保没有标头发送到客户端。您需要这样做,因为在该函数或事件之前,页面可能已发送了一些标头,例如内容类型或缓存控制。你需要Response.Clear因为页面可能在缓冲区中呈现了一些html。

答案 2 :(得分:0)

***

> HttpResponse.Buffer Property

***
Gets or sets a value indicating whether to buffer output and send it after the complete response is finished processing.
true if the output to client is buffered; otherwise, false.

***

> HttpResponse.Clear Method

***

Clears all content output from the buffer stream

The following example sets the ContentType property for the response to image/jpeg, calls the Clear method to remove other content that might be attached to the response, and then sets the BufferOutput property to true so that the complete page will be processed before any content is sent to the requesting client.

// Set the page's content type to JPEG files
// and clears all content output from the buffer stream.
Response.ContentType = "image/jpeg";
Response.Clear();

// Buffer response so that page is sent
// after processing is complete.
Response.BufferOutput = true;


***

> HttpResponse.ClearHeaders Method

***

Clears all headers from the buffer stream.

The following example calls the ClearHeaders method to ensure that no headers are sent with the current response. This technique can be especially important if the ASP.NET response is generating an image, such as a JPEG file. In this example the ContentType property is set to image/jpeg.


// Clear headers to ensure none
// are sent to the requesting browser
// and set the content type.
Response.ClearHeaders();
Response.ContentType = "image/jpeg";

-------------------------------------------------------------------------
summary :
asp.net keeps the header in a collection (Response.Headers) and the content in an output stream (Response.Output).

  Response.ClearHeaders - clears the current header collection
  Response.Clear - resets the output stream
  Response.ClearContent call Clear and is just a better name

all three will fail if Response.Buffer == false, and any output was been written.