ASP.NET 如何将文件流式传输给用户 [英] ASP.NET How To Stream File To User

查看:26
本文介绍了ASP.NET 如何将文件流式传输给用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初我试图弄清楚 Response.Close 和 Response.End 之间的区别,但在进行了更多的谷歌搜索和研究之后,很明显我没有看到 Byte[] 被发送回的常见方式客户端.我将保留下面的代码示例,但我想知道这样做的行业标准是什么.

Initially I was trying to figure out what the difference is between Response.Close and Response.End, but after doing more googling and research, its clear that I haven't seen a common way a Byte[] gets sent back to the client. I'll leave the code sample below, but I would like to know what the industry standard is for doing this.

Byte[] myBytes = GetReportBytes();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AppendHeader("content-length", myBytes.Length.ToString());
HttpContext.Current.Response.AppendHeader("content-Disposition", "attachment;filename=" + this.ReportFileName + GetReportExtension());
HttpContext.Current.Response.ContentType = GetApplicationContentType();
HttpContext.Current.Response.BinaryWrite(myBytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
//CERT FIX
//HttpContext.Current.Response.End();

推荐答案

我不会调用 Response.Close()Response.End().

Response.End() 将在此时停止页面执行/渲染.Response.End() 之后不会运行任何代码.响应在该点终止,没有进一步的输出添加到流中.

Response.End() will stop the page execution/rendering at that point. No code following Response.End() will be run. The response is terminated at that point with no further output added to the stream.

Response.Close()Response.End() 类似,但允许在调用后执行代码(但不能进一步输出页面响应).

Response.Close() is similar to Response.End(), but allows code to be executed after it is called (but no further output can be sent in the page response).

Response.Flush() 会将所有剩余的响应项发送到页面.

Response.Flush() will send any remaining response items to the page.

来自 IIS 核心团队成员:

Response.Close 向客户端并在任何事情中使用它除了错误条件将导致解决各种问题 - 例如,如果你正在与足够的客户交谈延迟,重置数据包可能导致缓冲的任何其他响应数据服务器、客户端或其他地方之间被丢弃.

Response.Close sends a reset packet to the client and using it in anything other than error condition will lead to all sorts of problems - eg, if you are talking to a client with enough latency, the reset packet can cause any other response data buffered on the server, client or somewhere in between to be dropped.

在这种特殊情况下,压缩涉及寻找常见模式在响应和一定数量的响应必须由压缩代码以增加找到更长重复的机会模式 - 这部分被缓冲一旦你不能发送给客户做 Response.Close().

In this particular case, compression involves looking for common patterns within the response and some amount of response has to be buffered by the compression code to increase the chance of finding longer repeating patterns - this part that is buffered cannot be sent to the client once you do Response.Close().

简而言之,不要使用Response.Close().

In short, do not use Response.Close().

这篇关于ASP.NET 如何将文件流式传输给用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆