Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HttpResponse download PDF

I was following tutorial on how to download pdf file using c# .net6 web api.
While following tutorial I did everything is showed but get difference response.

Code:

[HttpGet]
[Route("GetPdf")]
public HttpResponseMessage Get()
{
    HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

    string pdfLocation = _webHostEnvironment.WebRootPath + "\\PDF\\Biletas.pdf";

    var stream = new MemoryStream(System.IO.File.ReadAllBytes(pdfLocation));
    stream.Position = 0;

    if (stream == null)
    {
        result = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
        return result;
    }

    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

    result.Content.Headers.ContentDisposition.FileName = "FileTest.pdf";
    result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

    result.Content.Headers.ContentLength = stream.Length;


    return result;
}

I the tutorial file automatically downloads, but then I use the link I get JSON object and download does not start.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

JSON it shows then clicked on link.

{"version":"1.1","content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=FileTest.pdf"]},{"key":"Content-Type","value":["application/pdf"]},{"key":"Content-Length","value":["362671"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}

What I need to change to download pdf file?

>Solution :

Try return FileRasult instead of HttpResponseMessage.
This works for me:

[Route("GetPdf")]
public FileResult Get()
{
    string pdfLocation = _webHostEnvironment.WebRootPath + "\\PDF\\Biletas.pdf";
    
    var stream = new MemoryStream(System.IO.File.ReadAllBytes(pdfLocation));
    stream.Position = 0;

    var file = File(stream, "application/pdf", $"Biletas.pdf");

    return file;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading