Вернуть файл в ASP.NET Core Web API

Проблема

Я хочу вернуть файл в свой ASP.NET Web API Controller, но все мои подходы возвращают 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;
}

Когда я вызываю эту конечную точку в своем браузере, веб-API возвращает HttpResponseMessage как JSON с заголовком содержимого HTTP, установленным на application/json.

Ответы

Ответ 1

Если это asp.net-core, вы смешиваете версии web-api. получим действие return IActionResult, потому что в вашем текущем коде фрейм обрабатывает HttpResponseMessage как модель.

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        var stream = await {{__get_stream_here__}}
        var response = File(stream, "application/octet-stream"); // FileStreamResult
        return response;
    }    
}