C# – ASP.Net Core Content-Disposition attachment/inline

asp.net-corec

I am returning a file from a WebAPI controller. The Content-Disposition header value is automatically set to "attachment". For example:

Disposition: attachment; filename="30956.pdf"; filename*=UTF-8''30956.pdf

When it is set to attachment the browser will ask to save file instead of opening it. I would like it to open it.

How can I set it to "inline" instead of "attachment"?

I am sending the file using this method:

public IActionResult GetDocument(int id)
{
    var filename = $"folder/{id}.pdf";
    var fileContentResult = new FileContentResult(File.ReadAllBytes(filename), "application/pdf")
    {
        FileDownloadName = $"{id}.pdf"
    };
    // I need to delete file after me
    System.IO.File.Delete(filename);

    return fileContentResult;
}

Best Answer

The best way I have found is to add the content-disposition headers manually.

private IActionResult GetFile(int id)
{
       var file = $"folder/{id}.pdf";

       // Response...
       System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
       {
              FileName = file,
              Inline = displayInline  // false = prompt the user for downloading;  true = browser to try to show the file inline
       };
       Response.Headers.Add("Content-Disposition", cd.ToString());
       Response.Headers.Add("X-Content-Type-Options", "nosniff");

       return File(System.IO.File.ReadAllBytes(file), "application/pdf");
}