首页 文章

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

提问于
浏览
81

问题

我想在我的 ASP.Net Web API 控制器中返回一个文件,但我的所有方法都将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 Content Header 设置为application/json

1 回答

  • 159

    如果这是 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
        }    
    }
    

相关问题