Home > OS >  OkObjectResult with ContentTypes "application/pdf" some how is received by postman as 406
OkObjectResult with ContentTypes "application/pdf" some how is received by postman as 406

Time:12-07

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.

CodePudding user response:

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).

  • Related