2

我有一个带有按钮的 ASP Web 表单页面。在回发时,按钮将一些 XML 内容作为文件发送回用户。它一直在工作,但是在一个长度为 16759 的字符串的情况下,下载的文件被缩短了 10 个字节。Chrome 和 Firefox 都表现出相同的行为。

解决方案是将内容类型从“text/xml”(我也尝试过“text/plain”)更改为“application/octet-stream”。但是,我想了解为什么其他内容类型会以这种方式运行。

我的代码如下。(我玩过几种不同的方法,它们没有改变任何东西)

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("Content-Length", content.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"test.txt\"");
HttpContext.Current.Response.Write(content);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
4

1 回答 1

3

All you have to do is not call Close on the Stream. Don't ask me for an explanation, all I know is it works.

Explanation per the MSDN link for HttpResponse.Close kindly provided by Ray Cheng:

This method terminates the connection to the client in an abrupt manner and is not intended for normal HTTP request processing. The method sends a reset packet to the client, which can cause response data that is buffered on the server, the client, or somewhere in between to be dropped.

于 2012-06-21T06:41:46.750 回答