Show PDF in browser instead of downloading (ASP.NET MVC) without JavaScript

If I want to display a PDF file in the browser instead of downloading a copy, I can tell the browser via an additional Content-Disposition response header.

This code example assumes that the file content is available as byte-array, reading the content from a database, for example.

// Get action method that tries to show a PDF file in the browser (inline)
public ActionResult ShowPdfInBrowser()
  byte[] pdfContent = CodeThatRetrievesMyFilesContent();

  if (pdfContent == null)
    return null;

  var contentDispositionHeader = new System.Net.Mime.ContentDisposition
    Inline = true,
    FileName = "someFilename.pdf"

  Response.Headers.Add("Content-Disposition", contentDispositionHeader.ToString());
  return File(pdfContent, System.Net.Mime.MediaTypeNames.Application.Pdf);

Please keep in mind that ultimately we don’t have control over the browser. We can politely request to show the PDF inline, but this can be overridden by a user configuration, for example.

Leave a Reply