咨询区
Jan Kruse:
我想在 Web API 中返回 File 文件,我目前的做法是将 Action 返回值设为HttpResponseMessage
,参考代码如下:
publicasyncTask<HttpResponseMessage>DownloadAsync(stringid){varresponse=newHttpResponseMessage(HttpStatusCode.OK);response.Content=newStreamContent({{__insert_stream_here__}});response.Content.Headers.ContentType=newMediaTypeHeaderValue("application/octet-stream");returnresponse;}
当我在浏览器测试时,我发现Api将 HttpResponseMessage 作为 json格式返回,同时 Http Header 头为application/json
,请问我该如何正确配置成文件流返回。
回答区
H. Naeemaei:
我觉得大概有两种做法:
返回 FileStreamResult
[HttpGet("get-file-stream/{id}"]publicasyncTask<FileStreamResult>DownloadAsync(stringid){varfileName="myfileName.txt";varmimeType="application/....";Streamstream=awaitGetFileStreamById(id);returnnewFileStreamResult(stream,mimeType){FileDownloadName=fileName};}
返回 FileContentResult
[HttpGet("get-file-content/{id}"]publicasyncTask<FileContentResult>DownloadAsync(stringid){varfileName="myfileName.txt";varmimeType="application/....";byte[]fileBytes=awaitGetFileBytesById(id);returnnewFileContentResult(fileBytes,mimeType){FileDownloadName=fileName};}
Nkosi:
这是因为你的代码将 HttpResponseMessage 视为一个 Model,如果你的代码是 Core 的话,其实你可以混入一些其他特性,比如将你的 Action 返回值设置为一个派生自 IActionResult 下的某一个子类,参考如下代码:
[Route("api/[controller]")]publicclassDownloadController:Controller{//GETapi/download/12345abc[HttpGet("{id}")]publicasyncTask<IActionResult>Download(stringid){Streamstream=await{{__get_stream_based_on_id_here__}}if(stream==null)returnNotFound();//returnsaNotFoundResultwithStatus404NotFoundresponse.returnFile(stream,"application/octet-stream");//returnsaFileStreamResult}}
点评区
记得我在 webapi 中实现类似功能时,我用的就是后面这位大佬提供的方式,ActionResult + File
的方式,简单粗暴。