在ASP.NET Core应用程序中,当应用程序托管在IIS上并尝试从服务器下载大文件(500MB的zip文件)时,可能会遇到零字节的问题。这个问题的原因是Web服务器和客户端之间的连接超时。
要解决这个问题,可以通过在应用程序的Web.config文件中添加以下配置将IIS中的连接超时时间增加到300秒:
此外,还可以设置客户端下载文件时使用断点续传。以下为示例代码:
public async Task Download(int fileId, string fileName)
{
var memory = new MemoryStream();
using(var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return new FileStreamResult(memory, "image/jpeg")
{
FileDownloadName = fileName,
EnableRangeProcessing = true //enables resume downloads for browsers that support it
};
}
通过这两种方式,应用程序在IIS上托管时,下载大文件就不会出现0字节的问题了。