首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpResponseMessage内容无法显示

HttpResponseMessage内容无法显示
EN

Stack Overflow用户
提问于 2014-03-25 03:20:20
回答 2查看 23.9K关注 0票数 15

我已经创建了一个Web,它返回一个HttpResponseMessage,其中的内容被设置为一个PDF文件。如果我直接调用Web,它会工作得很好,而且PDF会在浏览器中呈现出来。

代码语言:javascript
复制
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:

代码语言:javascript
复制
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

当我点击调用web api的链接时,我得到了HttpResponseMessage的文本渲染。

代码语言:javascript
复制
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的设置……

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-26 02:53:33

经过几个小时的谷歌搜索和反复试验,我在这里解决了这个问题。

我没有将响应的内容设置为StreamContent,而是在WebApi端将其更改为ByteArrayContent。

代码语言:javascript
复制
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。

代码语言:javascript
复制
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 ...

代码语言:javascript
复制
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");

我希望这能对其他人有用,因为我已经浪费了很多时间来让它工作。

票数 24
EN

Stack Overflow用户

发布于 2019-10-18 14:20:09

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

代码语言:javascript
复制
public ActionResult GetPublicLink()



{
            path = @"D:\Read\x.pdf";
            return new PhysicalFileResult(path, "application/pdf");
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22618652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档