咨询区
- Jan Kruse: 
我想在 ASP.Net Web API 中返回 File 文件,我目前的做法是将 Action 返回值设为 HttpResponseMessage,参考代码如下:
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;
}当我在浏览器测试时,我发现Api将 HttpResponseMessage 作为 json格式返回,同时 Http Header 头为 application/json,请问我该如何正确配置成文件流返回。
回答区
- H. Naeemaei: 
我觉得大概有两种做法:
- 返回 FileStreamResult 
[HttpGet("get-file-stream/{id}"]public async Task<FileStreamResult> DownloadAsync(string id){var fileName="myfileName.txt";var mimeType="application/...."; Stream stream = await GetFileStreamById(id);return new FileStreamResult(stream, mimeType){FileDownloadName = fileName};}- 返回 FileContentResult 
[HttpGet("get-file-content/{id}"]public async Task<FileContentResult> DownloadAsync(string id){var fileName="myfileName.txt";var mimeType="application/...."; byte[] fileBytes = await GetFileBytesById(id);return new FileContentResult(fileBytes, mimeType){FileDownloadName = fileName};}- Nkosi: 
这是因为你的代码将 HttpResponseMessage 视为一个 Model,如果你的代码是 Asp.NET Core 的话,其实你可以混入一些其他特性,比如将你的 Action 返回值设置为一个派生自 IActionResult 下的某一个子类,参考如下代码:
[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}    
}点评区
记得我在 webapi 中实现类似功能时,我用的就是后面这位大佬提供的方式, ActionResult + File 的方式,简单粗暴。