Search code examples
c#asp.net-core.net-coreasp.net-core-webapi

Return file in ASP.Net Core Web API


Problem

I want to return a file in my ASP.Net Web API Controller, but all my approaches return the HttpResponseMessage as JSON.

Code so far

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;
}

When I call this endpoint in my browser, the Web API returns the HttpResponseMessage as JSON with the HTTP Content Header set to application/json.


Solution

  • If this is ASP.NET Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

    [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", "{{filename.ext}}"); // returns a FileStreamResult
        }    
    }
    

    Note:

    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.