我正在创建一个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>
现在,当我从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.
关于这里发生了什么的任何想法以及如何解决这种奇怪的行为?