ASP.Net Core Web API 如何返回 File。
生活随笔
收集整理的這篇文章主要介紹了
ASP.Net Core Web API 如何返回 File。
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
咨詢區(qū)
Jan Kruse:
我想在 ASP.Net Web API 中返回 File 文件,我目前的做法是將 Action 返回值設(shè)為 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; }當(dāng)我在瀏覽器測試時,我發(fā)現(xiàn)Api將 HttpResponseMessage 作為 json格式返回,同時 Http Header 頭為 application/json,請問我該如何正確配置成文件流返回。
回答區(qū)
H. Naeemaei:
我覺得大概有兩種做法:
返回 FileStreamResult
返回 FileContentResult
Nkosi:
這是因為你的代碼將 HttpResponseMessage 視為一個 Model,如果你的代碼是 Asp.NET Core 的話,其實你可以混入一些其他特性,比如將你的 Action 返回值設(shè)置為一個派生自 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}???? }點評區(qū)
記得我在 webapi 中實現(xiàn)類似功能時,我用的就是后面這位大佬提供的方式, ActionResult + File 的方式,簡單粗暴。
總結(jié)
以上是生活随笔為你收集整理的ASP.Net Core Web API 如何返回 File。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Pitcher简化卫语句
- 下一篇: Dapr牵手.NET学习笔记:开篇