【问题标题】:HttpException on OutputStream. How to correctly send fileOutputStream 上的 HttpException。如何正确发送文件
【发布时间】:2011-12-05 09:01:04
【问题描述】:

我使用下面的代码将文件从 ASP.NET Rest Api 发送到客户端。有时我会看到错误日志“远程主机关闭了连接。错误代码是 0x800703E3。”这是发送流响应的正确方法吗?

var outputFileName;                   
context.Response.ContentType = WebHelper.GetMimeType(outputFileName);
context.Response.AddHeader("Content-Disposition", string.Format("{0}; filename={1}", "attachment", outputFileName));
context.Response.AddHeader("Content-Length", binaryData.Length.ToString());
context.Response.OutputStream.Write(binaryData, 0, binaryData.Length);
context.Response.Flush();
context.Response.Close();

【问题讨论】:

    标签: c# asp.net file httpresponse


    【解决方案1】:

    如果文件中有数据,使用Response.TransmitFile 比使用 Response.OutputStream.Write 好得多,因为 TransmitFile 不会在内存中缓冲文件数据。

    至于您收到的错误消息,这是完全正常的。如果用户在传输文件时断开网络连接、取消下载或关闭浏览器,则会出现此错误消息,让您知道传输未完成。

    【讨论】:

    • Response.TransmitFile 不支持内存文件传输,在我的情况下,我的磁盘上没有文件,它在内存中。
    • @Tomas:好的,我没有从您的代码中看到您之前是否从文件中加载了数据,所以我认为值得一提。但是,有关错误消息的信息也适用于您的情况。
    【解决方案2】:

    这个这个:

    context.Response.Clear();
    
    context.Response.ContentType = ...;
    context.Response.AddHeader( "Content-Disposition", ... );
    // do not set Content-Length
    context.Response.Write( binaryData );
    context.Response.Flush();
    context.Response.End();
    

    【讨论】:

    • 您能解释一下您的代码吗?为什么没有设置内容长度?我认为在向用户发送文件时隐藏响应长度并不是一个好主意。
    • 如果缺少内容长度,应该由引擎自动添加。这样,标头中声明的内容长度与实际内容长度之间应该没有不一致。我认为这种不一致是您获得异常的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多