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}

  • output:

**

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

1 Answers1

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

Rena
  • 30,832
  • 6
  • 37
  • 72