파일 컨텐츠를 반환하면 asp.net web api
filecontentResult
는 MVC 컨트롤러에서 pdfs와 같은 파일을 제공하기 위해 잘 작동하며 apicontroller
로 직접 포팅하면 문제가 발생합니다. StreamContent
를 사용하려는 간단한 시도는 종종 실패하여 파일 자체 대신 JSON 메타 데이터를 초래합니다. 솔루션은 BytearRayContent
를 활용하는 데 있습니다.
이 개정 된 코드 스 니펫은 웹 API의 결과로 파일 내용으로 PDF 파일을 효과적으로 반환합니다 :
[HttpGet]
public HttpResponseMessage Generate()
{
using (var stream = new MemoryStream())
{
// Process the stream to generate PDF content here...
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
키는 BytearRayContent
를 사용하여 파일의 바이트를 캡슐화하고 contentDisPosition
헤더를 "첨부 파일"으로 설정하여 다운로드를 자극합니다. contentType
헤더는 클라이언트의 적절한 처리를 보장합니다. 를 사용하여
를 사용하여 memorystream
가 제대로 배치되도록하십시오. 이 접근 방식은 웹 API를 통해 PDF 및 기타 파일 유형을 완벽하게 전달할 수 있습니다.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3