asp.net-mvc – HttpResponseMessage内容不会显示PDF
发布时间:2020-12-15 22:51:42 所属栏目:asp.Net 来源:网络整理
导读:我创建了一个Web Api,返回一个HttpResponseMessage,其中内容被设置为PDF文件.如果我直接调用Web Api,它的效果很好,PDF在浏览器中呈现. response.Content = new StreamContent(new FileStream(pdfLocation,FileMode.Open,FileAccess.Read)); response.Content
我创建了一个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; 我有一个想要联系Web Api的MVC客户端,请求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,file.Length); outputStream.Position = 0; return File(outputStream,"application/pdf"); 我希望这可以对别人有用,因为我浪费了很多时间让它工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 如何在asp.net c中以pdf格式导出同步图表
- 对于ASP.Net中的IIS管理哪个更好:WMI或ADSI或托管API?有什
- asp.net html控件的File控件实现多文件上传实例分享
- asp.net-mvc – 在数据实体框架中显示名称
- asp.net – 检测Internet Explorer浏览器版本问题
- asp.net – 在web-farm网站上将machineKey添加到web.config
- asp.net – 我有多个用户,我可以锁定网页,以便一次只有一个
- asp.net-mvc-3 – 为什么WebGrid在格式化中使用动态?
- Asp:文本框与输入文本(PHP开发人员学习ASP)
- asp.net-mvc-3 – 以下部分已定义,但尚未为布局页面呈现
推荐文章
站长推荐
- asp.net-mvc – 带SelectList Design Decison的V
- 三重报价?如何在ASP.NET中分隔数据绑定的JavaSc
- asp.net-mvc – 使用MVC为iPhone应用构建RESTful
- asp.net-mvc – AntiForgeryToken登录后无效
- asp.net-mvc-3 – 如何从ASP.NET MVC#输出中删除
- asp.net – 自定义日期colmn telerik网格的过滤器
- 在ASP.NET网站中使用SQL Server Compact Edition
- asp.net-mvc – Asp.net Web api异常仅在IIS部署
- asp.net-mvc – Signalr从集线器外部调用特定客户
- 从头编写 asp.net core 2.0 web api 基础框架 (1
热点阅读