问题
我想在我的 ASP.Net Web API Controller 中返回一个文件,但我所有的方法都将 HttpResponseMessage
作为 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 内容 header 设置为 application/json
。
最佳答案
如果这是 ASP.net-Core,那么您正在混合 Web API 版本。让操作返回派生的 IActionResult
,因为在您当前的代码中,框架将 HttpResponseMessage
视为模型。
[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
}
}
注意:
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.
关于c# - ASP.Net Core Web API 中的返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460198/