使用Asp.net核心将PDF返回到浏览器
我在ASP.Net核心中创建了Wep API以返回PDF.这是我的代码:
public HttpResponseMessage Get(int id) { var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); var stream = new System.IO.FileStream(@"C:Usersshoba_eswarDocumentsREquest.pdf",System.IO.FileMode.Open); response.Content = new StreamContent(stream); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = "NewTab"; response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"); return response; } 但它只返回JSON响应: { "version":{ "major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1 },"content":{ "headers":[ { "key":"Content-Disposition","value":[ "attachment; filename=NewTab" ] },{ "key":"Content-Type","value":[ "application/pdf" ] } ] },"statusCode":200,"reasonPhrase":"OK","headers":[ ],"requestMessage":null,"isSuccessStatusCode":true } 我在这做错了吗? 解决方法
如
ASP.NET Core HTTPRequestMessage returns strange JSON message中所述,ASP.NET Core不支持返回HttpResponseMessage(您安装了哪些软件包以访问该类型?).
因此,序列化程序只是将HttpResponseMessage的所有公共属性写入输出,就像使用任何其他不受支持的响应类型一样. 要支持自定义响应,您必须返回IActionResult实现类型.有plenty of those.在你的情况下,我会调查 public IActionResult Get(int id) { using (var stream = new FileStream(@"pathtofile",FileMode.Open)) { return new FileStreamResult(stream,"application/pdf"); } } 或者只需使用 public IActionResult Get(int id) { return new FileStreamResult(@"pathtofile","application/pdf"); } 当然所有这些都可以使用辅助方法简化,例如Controller.File(): public IActionResult Get(int id) { using (var stream = new FileStream(@"pathtofile",FileMode.Open)) { return File(stream,"application/pdf","FileDownloadName.ext"); } } 这简单地抽象了FileContentResult或FileStreamResult的创建(对于这个重载,后者). 或者,如果您要转换较旧的MVC或Web API应用程序并且不想一次转换所有代码,请添加对WebApiCompatShim (NuGet)的引用并将当前代码包装在 public IActionResult Get(int id) { var response = new HttpResponseMessage(HttpStatusCode.OK); var stream = ... response.Content... return new ResponseMessageResult(response); } 如果您不想使用返回文件(fileName,contentType,fileDownloadName),则FileStreamResult不支持从构造函数或通过属性设置content-disposition标头. 在这种情况下,您必须在返回文件结果之前自己将响应标头添加到响应中: var contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName("foo.txt"); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 如何在非ASP.NET应用程序中使用ASP.NET Cache对象?
- asp.net-web-api – 如何使用OWIN自动主机的web api来提供i
- asp.net – 以编程方式将几个地址添加到谷歌地图中
- asp-classic – 经典Asp页面中的Url重定向
- asp.net-mvc – Controller如何知道MVC中DeleteConfirmed的
- asp.net-core-mvc – 在EF7中加载引用
- asp.net – #Eval if语句在中继器
- asp.net-mvc – 获取Route,ASP.net MVC中的当前片段
- asp.net-core – ASP.NET 5中的Application_Start等价物
- asp.net-mvc-3 – MvcContrib网格和复选框