views:

37

answers:

2

To send pdf files (or any other file type) to the browser, I've seen examples that use the FileResult class or a custom Action Result.

Is there an advantage of using one over the other? Thanks

A: 

EDIT Original reply removed.

I'm not sure if the exist file result allows to you modify the content disposition, I believe it forces the content disposition of "attachment". If you want to use a different disposition, I'd implement a custom Action Filter:

/// <summary>
/// Defines an <see cref="ActionResult" /> that allows the output of an inline file.
/// </summary>
public class InlineFileResult : FileContentResult
{
    #region Constructors
    /// <summary>
    /// Writes the binary content as an inline file.
    /// </summary>
    /// <param name="data">The data to be written to the output stream.</param>
    /// <param name="contentType">The content type of the data.</param>
    /// <param name="fileName">The filename of the inline file.</param>
    public InlineFileResult(byte[] data, string contentType, string fileName)
        : base(data, contentType)
    {
        FileDownloadName = fileName;
    }
    #endregion

    #region Methods
    /// <summary>
    /// Executes the result, by writing the contents of the file to the output stream.
    /// </summary>
    /// <param name="context">The context of the controller.</param>
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null) {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = this.ContentType;
        if (!string.IsNullOrEmpty(this.FileDownloadName)) {
            ContentDisposition disposition = new ContentDisposition();
            disposition.FileName = FileDownloadName;
            disposition.Inline = true;
            context.HttpContext.Response.AddHeader("Content-Disposition", disposition.ToString());
        }

        WriteFile(response);
    }
    #endregion
}

That is one I've used previously, because I pass the actual byte[] data of the file.

Matthew Abbott
Sorry, I meant ActionResult (and implementing ExecuteResult) and not ActionFilter. Corrected title.
DotnetDude
A: 

They would essentially do the same thing. Setting up a FileContentResult is probably the most straight-forward and easiest to get started with:

public FileContentResult GetPdf()
{
    return File(/* byte array contents */, "application/pdf");
}

If you wanted to save yourself from having to specify the content type (if you are always going to do PDF), you could create an ActionResult that specified the content type (application/pdf) inside of it, and return that instead of the FileContentResult (maybe something like PdfContentResult).

But like I said, they will do the same thing and there will not be any performance difference.

mc2thaH