HttpResponseMessage的内容无法显示PDF。

15

我创建了一个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...

任何帮助都将不胜感激。 谢谢

2个回答

26

经过数小时的谷歌搜索和尝试,我终于在这里解决了这个问题。

与其将响应的内容设置为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");

我希望这对其他人有用,因为我浪费了很多时间才让它正常工作。


1
我也从Web API向客户端返回一个字节数组。我想在客户端上将该字节数组作为PDF下载。你如何处理输出流中得到的响应? - user2585299
上面的第二和第三段代码显示了它。我在Web上创建了一个客户端,并将Web Api的url传递给它。Web客户端从Web Api中获取Byte[],并将其转换为MemoryStream(以便我不会将文件保存在本地),然后将其作为PDF文件返回给Web客户端(浏览器)。 - user2163049
2
我的API控制器上有[Authorize]属性。我不能直接从Web API发送文件。我必须在ajax请求完成后在客户端处理byte[]。data = "data:application/octet-stream;base64," + data; document.location = data; 这些行确实下载了文件,但文件没有任何名称或扩展名。我只看到一个名为“download”的文件名。如何在客户端设置文件名? - user2585299
这是我如何命名文件,但我是在服务器上执行的... Response.AddHeader("Content-Disposition", "inline; filename="+ fileName); - user2163049

-1

只需返回PhysicalFileResult并使用HttpGet方法,URL将打开PDF文件

public ActionResult GetPublicLink()



{
            path = @"D:\Read\x.pdf";
            return new PhysicalFileResult(path, "application/pdf");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接