Home > Net >  HttpResponse download PDF
HttpResponse download PDF

Time:12-27

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.

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?

CodePudding user response:

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;
}
  • Related