首页 > 解决方案 > 直接写入 HttpResponse 时 WCF REST 失败网络错误

问题描述

我正在创建一个 WCF REST Web 服务,用于下载大文件(可能超过 2GB)。这些文件是不存储在硬盘驱动器上的 csv 文件,而是在发出请求时在运行时形成的。正因为如此,我选择将 csv 文件直接写入HttpResponse避免任何不会容纳超过 2GB 数据的中间容器。这是我写的一个测试代码,它符合我的描述:

[ServiceContract]
public interface IDownloadService
{
    [OperationContract]
    [WebInvoke(
        Method = "GET",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "")]
    void Download();
}

public class DownloadService : IDownloadService
{
    public void Download()
    {
        var response = HttpContext.Current.Response;
        response.Clear();
        response.ContentType = "application/csv";
        response.AddHeader("Content-Disposition", "attachment; filename=myfile.csv");

        //This is a small test csv file, it will be replaced with a big file,
        //that will be formed in runtime and written piece by piece into Response.OutputStream
        response.BinaryWrite(System.Text.Encoding.UTF8.GetBytes("1,2,3"));
        response.Flush();
        response.Close();
        response.End();
    }
}

这是我的Web.config,以防万一:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="RestWcf.DownloadService">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" contract="RestWcf.IDownloadService"/>
      </service>
    </services>   
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>

现在这是有趣的部分,当我从 调用这个 webservice 方法时Google Chrome,首先它开始下载文件,在下载 Chrome 结束时给我错误Failed - Network error,当我尝试调用它时,Postman我收到Could not get any response消息但没有生成响应,最后当我尝试从Fiddler我收到 504 响应中调用它,并提供更多信息ReadResponse() failed: The server did not return a complete response for this request. Server returned 384 bytes.

关于这里发生了什么以及如何解决这种奇怪行为的任何想法?

标签: wcfstreaminghttpresponsewcf-resthttp-streaming

解决方案


推荐阅读