2

With Postman, I am sending to my service a GET request with Header to Accept "application/pdf" and Accept-Encoding "gzip, deflate, br, *".

On code side,

    byte[] pdf_test = System.IO.File.ReadAllBytes(@"C:\somewhere\hello.pdf");
    OkObjectResult output = new OkObjectResult(pdf_test); // uncomment below once done.
    
    output.ContentTypes.Add(@"application/pdf"); // LINE IN QUESTION

    // And finally, back to the remote caller.
    return output;

When I debug this code, the status code is 200, and ContentTypes having "aplication/pdf". With Value having all the bytes of pdf.

When postman receives the response, I see the return code as 406 Not Acceptable.

The weird thing is, when I comment out the "LINE IN QUESTION" from above, the Postman receives message with 200 OK. But Content-Type accepted as "application/json".

Why is this occuring?

Postman ultimately does not matter but real program is expecting "application/pdf" content type, this real program does not exist yet. So at least I would like to get my side correctly done.

Thanks in advance.

Shintaro Takechi
  • 1,215
  • 1
  • 17
  • 39

1 Answers1

3

To return the content of a file, you'd better use a FileStreamResult.

var stream = System.IO.File.OpenRead(@"C:\somewhere\hello.pdf");
return new FileStreamResult(stream, "application/pdf");

The OkObjectResult is involved in content negotiation and formatting.
From the documentation:

An ObjectResult that when executed performs content negotiation, formats the entity body, and will produce a Status200OK response if negotiation and formatting succeed.

This should not take place here to return a byte-array/stream.

The source code at GitHub shows that the HTTP status code 406 Not Acceptable gets set when executing the OkResultObject since there's no formatter present (for content type application/pdf).

pfx
  • 20,323
  • 43
  • 37
  • 57
  • Thank you so much for the answer. For my case, I needed to use byte array coming from elsewhere so FileContentResult was much fitting in this case, but basic concept is understood from your answer. (reference for FileContentResult : https://stackoverflow.com/a/57524973/1076116) – Shintaro Takechi Dec 06 '21 at 22:22