我已经创建了一个Web,它返回一个HttpResponseMessage,其中的内容被设置为一个PDF文件。如果我直接调用Web,它会工作得很好,而且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文件,然后以同样的方式呈现给用户。
不幸的是,我不确定问题出在哪里,但即使我设置了content-type:
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的设置……
任何帮助都将不胜感激。谢谢
发布于 2014-03-26 02:53:33
经过几个小时的谷歌搜索和反复试验,我在这里解决了这个问题。
我没有将响应的内容设置为StreamContent,而是在WebApi端将其更改为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");通过这种方式,我的MVC4应用程序能够使用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");我希望这能对其他人有用,因为我已经浪费了很多时间来让它工作。
发布于 2019-10-18 14:20:09
只需返回PhysicalFileResult并使用HttpGet方法,url将打开pdf文件
public ActionResult GetPublicLink()
{
path = @"D:\Read\x.pdf";
return new PhysicalFileResult(path, "application/pdf");
}https://stackoverflow.com/questions/22618652
复制相似问题