1

The below code is returning JSON object instead of downloading the PDF file:

var dataStream = new MemoryStream(System.IO.File.ReadAllBytes(@"C:\data\test12.pdf"));
                dataStream.Position = 0;
                HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
                responseMsg.Content = new StreamContent(dataStream);
                responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline");
                responseMsg.Content.Headers.ContentDisposition.FileName = file.Rows[0][1].ToString();
                responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                responseMsg.Content.Headers.ContentLength = dataStream.Length;
                result = responseMsg;

output:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["inline; filename=4159a9f5-0102-46c3-a39f-7449c00e39e5.pdf"]},{"key":"Content-Type","value":["application/pdf"]},{"key":"Content-Length","value":["7874"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

4
  • Your code does not return anything currently - it is missing a return statement. Could you add a bit more context? Commented Oct 19, 2022 at 7:51
  • public HttpResponseMessage get(long id){ var dataStream = new MemoryStream(System.IO.File.ReadAllBytes(@"C:\data\test12.pdf")); .......... return result; } Commented Oct 19, 2022 at 8:21
  • 1
    Please add everything relevant to your question. Use the edit button. Commented Oct 19, 2022 at 9:15
  • Hi, any update here? Commented Oct 24, 2022 at 1:15

1 Answer 1

1

The below code is returning JSON object instead of downloading the pdf file.

This is the expected result when you call this api. In your current code the framework is treating HttpResponseMessage as a model.

The correct way to download a file after calling the api should be:

public IActionResult Get()
{
    var dataStream = new MemoryStream(System.IO.File.ReadAllBytes(@"C:\data\test12.pdf"));
    Response.Headers.Add("Content-Disposition", "inline; filename=test.pdf");
    return File(dataStream, "application/pdf");
}

If you want to use HttpResponseMessage, you need call the api by ajax.

Reference: https://stackoverflow.com/a/41115583/11398810

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.