asp.net-mvc – HttpResponseMessage内容不会显示PDF
发布时间:2020-05-24 06:05:29 所属栏目:asp.Net 来源:互联网
导读:我创建了一个Web Api,返回一个HttpResponseMessage,其中内容被设置为PDF文件.如果我直接调用Web Api,它的效果很好,PDF在浏览器中呈现. response.Content = new StreamContent(new FileStream(pdfLocation, FileMode.Open, FileAccess.Read)); respons
|
我创建了一个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-mvc – MVC DateTime文本框格式化问题
- asp.net-mvc – 为什么我的HttpConfiguration类型没有使用.
- 这个ASP.NET顾问知道他在做什么?
- asp.net-mvc – 带有asp.net mvc 4和EntityFramework的View
- asp.net – 什么是global.asax用于?
- ASP.Net MVC如何将数据从视图传递到控制器
- asp.net-mvc – 在ASP.NET MVC中实现“记住我”功能
- 简明的ASP.NET验证摘要
- asp.net – 无法自动进入服务器.无法确定停止位置
- asp.net-mvc – “信号量超时期限已过期”SQL Azure
推荐文章
站长推荐
- ASP.NET MVC:使用LINQ To SQL获取表单复选框到多
- asp.net-mvc – 如何gzip内容在asp.net MVC?
- asp.net – 任何方式构建Google文档,如PDF文件的
- asp.net-web-api – 如何设置Elmah与ASP.NET Web
- asp.net – 使用CompareValidator控件将用户输入
- asp.net-mvc-3 – 自定义ActionInvoker与MVC 3中
- asp.net – 验证失败后如何防止页面跳转到顶部位
- asp.net-mvc – 奇怪的错误w / NinjectValidator
- asp.net – System.Diagnostics.Process.Start不
- asp.net-mvc – 如何在Ajax窗体的asp.net mvc中提
热点阅读
