Return PDF to the Browser using ASP.NET Core

前端 未结 3 599
天涯浪人
天涯浪人 2020-11-28 06:09

I created the Wep API in ASP.Net core to return the PDF. Here is my code:

public HttpResponseMessage Get(int id)
{
    var response = new HttpResponseMessage         


        
3条回答
  •  长情又很酷
    2020-11-28 06:25

    I couldn't comment the answer by CodeCaster since my reputation isn't high enough. When trying

    public IActionResult Get(int id)
    {
        using (var stream = new FileStream(@"path\to\file", FileMode.Open))
        {
            return File(stream, "application/pdf", "FileDownloadName.ext");
        }       
    } 
    

    we got a

    ObjectDisposedException: Cannot access a disposed object. Object name: 'Cannot access a closed file.'. System.IO.FileStream.BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object state)

    We removed the using

       [HttpGet]
       [Route("getImageFile")]
       public IActionResult GetWorkbook()
       {
            var stream = new FileStream(@"pathToFile", FileMode.Open);
            return File(stream, "image/png", "image.png");
       }
    

    And that worked. This is ASP.NET Core 2.1 running in IIS Express.

提交回复
热议问题