ASP WebAPI 2 _pdf HTTPResponseMessage_couldnt open

49 Views Asked by At

Used the below code to read a pdf file and return as response from WebAPI 2. When I used a text file here and also changed the response FileName="new.txt", then it works fine. Running the WEBAPI in swagger, could download file in the response and the file opens too.

But if its a pdf file, the downloaded file couldnt be opened. Also tried zip and xl files....File is corrupted and couldnt be opened.

        [HttpGet]
        [Route("GetPDF")]
        public IHttpActionResult GetABCPDF()
        {
          var bytes = System.IO.File.ReadAllBytes(bookPath_Pdf);
          var dataStream = new MemoryStream(bytes);
          HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(dataStream)
            };
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "new.pdf"
            };
            httpResponseMessage.Content.Headers.ContentLength = dataStream.Length;
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
            return responseMessageResult;
        }
0

There are 0 best solutions below