Programing

ASP.Net Core Web API의 반환 파일

crosscheck 2020. 9. 12. 09:07
반응형

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

브라우저에서이 끝점을 호출하면 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
    }    
}

참고 URL : https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api

반응형