문제
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;
}
브라우저에서이 끝점을 호출하면 Web API는 HttpResponseMessageHTTP 콘텐츠 헤더가 application/json.
답변
이것이 ASP.net-Core이면 웹 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
    }
}
답변
다음 메서드를 사용하여 FileResult를 반환 할 수 있습니다.
1 : FileStreamResult 반환
    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/....";
        var stream = await GetFileStreamById(id);
        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }
2 : FileContentResult 반환
    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/....";
        var fileBytes = await GetFileBytesById(id);
        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }
답변
다음은 파일 스트리밍의 간단한 예입니다.
using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
    var path = "<Get the file path using the ID>";
    var stream = File.OpenRead(path);
    return new FileStreamResult(stream, "application/octet-stream");
}
노트 :
사용하십시오 FileStreamResult에서 Microsoft.AspNetCore.Mvc와 하지 에서 System.Web.Mvc.
