我创建了一个 Web Api,它返回一个 HttpResponseMessage,其中内容设置为 PDF 文件。如果我直接调用 Web Api,它会很好地工作,并且 PDF 会在浏览器中呈现。
response.Content = new StreamContent(new FileStream(pdfLocation, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Headers.ConnectionClose = true;
return response;
我有一个 MVC 客户端,想要联系 Web Api、请求 Pdf 文件,然后以与上述相同的方式将其呈现给用户。
不幸的是,我不确定问题出在哪里,但即使我设置了内容类型:
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
当我单击调用 Web API 的链接时,我会得到 HttpResponseMessage 的文本呈现。
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: close Content-Disposition: attachment Content-Type: application/pdf }
我认为客户端应用程序缺少一些设置,使其能够像我的 Web Api 一样呈现 PDF...
如有任何帮助,我们将不胜感激。 谢谢
最佳答案
经过几个小时的 Google 搜索以及反复试验,我已经解决了这里的问题。
我没有将响应内容设置为 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");
我希望这对其他人有用,因为我已经浪费了很多时间来让它工作。
关于asp.net-mvc - HttpResponseMessage 内容不会显示 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22618652/