如何从 ASP.net 5 web api 返回文件

编程入门 行业动态 更新时间:2024-10-18 10:25:17
本文介绍了如何从 ASP 5 web api 返回文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 asp 5 中创建了 wep api.我想为 Post 请求返回文件响应.但是,而不是文件的响应看起来像`

Created wep api in asp 5. I am tring to return file response for Post request. But instead of file the response looks like `

{ "version": { "major": 1, "minor": 1, "build": -1, "revision": -1, "majorRevision": -1, "minorRevision": -1 }, "content": { "headers": [ { "key": "Content-Disposition", "value": [ "attachment; filename=test.pdf" ] }, { "key": "Content-Type", "value": [ "application/pdf" ] } ] }, "statusCode": 200, "reasonPhrase": "OK", "headers": [], "requestMessage": null, "isSuccessStatusCode": true }`

代码:

public HttpResponseMessage Post([FromBody]DocumentViewModel vm) { try { if (ModelState.IsValid) { var Document = _repository.GetDocumentByGuid(vm.DocumentGuid, User.Identity.Name); var Params = Helper.ClientInputToRealValues(vm.Parameters, Document.DataFields); var file = Helper.GeneratePdf(Helper.InsertValues(Params, Document.Content)); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(System.IO.File.ReadAllBytes(file)) }; result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "test.pdf" }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return result; } } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return null; } Response.StatusCode = (int)HttpStatusCode.BadRequest; return null; }

如何将真实文件作为响应而不是 JSON 返回?我使用 Postman 作为测试客户端.

How can I return the real file as the response instead of JSON ?I am using Postman as test client.

推荐答案

使用 IActionResult 而不是 HttpResponseMessage.并返回 FileStreamResult,并使其正常工作.

used IActionResult instead of HttpResponseMessage. And returned FileStreamResult, and got it working.

遇到一个新问题,该文件不是我用来自服务器的流打开的文件.但是会为此创建一个新问题.

Got a new problem, the file is not the one I open with the stream from server. But will create a new question for that.

继续:从 ASP.NET 5 Web API 返回文件

谢谢

更多推荐

如何从 ASP.net 5 web api 返回文件

本文发布于:2023-11-13 15:09:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584665.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   net   ASP   api   web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!