WebAPI 2 Return A File`s Contents - 1/15/2015

So this should not be this hard, but it took some experimenting to figure out.

Suppose we have a little class

/// <summary>
/// File Info
/// </summary>
public class FileInfo
    /// <summary>
    /// Contents of a file
    /// </summary>
    public byte[] Contents { get; set; }
    /// <summary>
    /// Mime type
    /// </summary>
    public string MimeType { get; set; }

And now we want to use this class to make a WebAPI method to return the file, along with the correct mime type

public HttpResponseMessage GetFileContentsById(int id)
    // use args to get a FileInfo object
    var fi = GetFileInfo(id);

    // Now format and send it back
    var response = Request.CreateResponse(HttpStatusCode.OK);
    var ms = new System.IO.MemoryStream(fi.Contents);
    response.Content = new StreamContent(ms);
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(fi.MimeType);
    // Force No-Cache on the return
    response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true };
    return response;

And presto, we can return the contents of a file. This is especially good for Images (PNG, JPG, GIF), Documents (PDF, DOCX, etc.)

Blog ID: 2015 Blog_635568768000000000