经过几个小时的谷歌搜索以及反复试验,我已经解决了这里的问题。
我没有将响应内容设置为 StreamContent,而是在 Web Api 端将其更改为 ByteArrayContent。
byte[] fileBytes = System.IO.File.ReadAllBytes(pdfLocation);
response.Content = new ByteArrayContent(fileBytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
通过这种方式,我的 MVC 4 应用程序能够使用 WebClient 和 DownloadData 方法下载 PDF。
internal byte[] DownloadFile(string requestUrl)
{
string serverUrl = _baseAddress + requestUrl;
var client = new System.Net.WebClient();
client.Headers.Add("Content-Type", "application/pdf");
return client.DownloadData(serverUrl);
}
返回的 Byte[] 数组可以在返回文件进行输出之前轻松转换为 MemoryStream...
Response.AddHeader("Content-Disposition", "inline; filename="+fileName);
MemoryStream outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(outputStream, "application/pdf");
我希望这对其他人有用,因为我已经浪费了很多时间来让它工作。