在 ASP.Net Core Web API 中返回文件

编程入门 行业动态 更新时间:2024-10-18 08:35:18
本文介绍了在 ASP.Net Core Web API 中返回文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在我的 ASP.Net Web API 控制器中返回一个文件,但我所有的方法都将 HttpResponseMessage 作为 JSON 返回.

I want to return a file in my ASP.Net Web API Controller, but all my approaches return the HttpResponseMessage as JSON.

public async Task<HttpResponseMessage> DownloadAsync(string id) { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent({{__insert_stream_here__}}); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return response; }

当我在浏览器中调用此端点时,Web API 将 HttpResponseMessage 作为 JSON 返回,并将 HTTP 内容标头设置为 application/json.

When I call this endpoint in my browser, the Web API returns the HttpResponseMessage as JSON with the HTTP Content Header set to application/json.

推荐答案

如果这是 ASP-Core,那么您正在混合 Web API 版本.让操作返回派生的 IActionResult,因为在您当前的代码中,框架将 HttpResponseMessage 视为模型.

If this is ASP-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

[Route("api/[controller]")] public class DownloadController : Controller { //GET api/download/12345abc [HttpGet("{id}")] public async Task<IActionResult> Download(string id) { Stream stream = await {{__get_stream_based_on_id_here__}} if(stream == null) return NotFound(); // returns a NotFoundResult with Status404NotFound response. return File(stream, "application/octet-stream"); // returns a FileStreamResult } }

注意:

当响应完成时,框架将处理在这种情况下使用的流.如果使用 using 语句,流将在响应发送之前被释放,并导致异常或损坏响应.

The framework will dispose of the stream used in this case when the response is completed. If a using statement is used, the stream will be disposed before the response has been sent and result in an exception or corrupt response.

更多推荐

在 ASP.Net Core Web API 中返回文件

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

发布评论

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

>www.elefans.com

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