asp.netasp.net-mvcasp.net-web-api

Returning binary file from controller in ASP.NET Web API


I'm working on a web service using ASP.NET MVC's new WebAPI that will serve up binary files, mostly .cab and .exe files.

The following controller method seems to work, meaning that it returns a file, but it's setting the content type to application/json:

public HttpResponseMessage<Stream> Post(string version, string environment, string filetype)
{
    var path = @"C:\Temp\test.exe";
    var stream = new FileStream(path, FileMode.Open);
    return new HttpResponseMessage<Stream>(stream, new MediaTypeHeaderValue("application/octet-stream"));
}

Is there a better way to do this?


Solution

  • Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

    // using System.IO;
    // using System.Net.Http;
    // using System.Net.Http.Headers;
    
    public HttpResponseMessage Post(string version, string environment,
        string filetype)
    {
        var path = @"C:\Temp\test.exe";
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = 
            new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }
    

    A few things to note about the stream used: