How to return Binary File from a Action Method in ASP.NET Web API ?

There are times when you might want to serve binary files from your controller’s action method in ASP.NET MVC Web API. You can do this easily by setting the octet-stream content for the HttpResponseMessage as shown in the code snippet.

How to return Binary File from a Action Method in ASP.NET Web API ?

public HttpResponseMessage Post()
{
    HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new System.IO.FileStream(@"C:\acFile.exe", System.IO.FileMode.Open);
    retValue.Content = new StreamContent(stream);
    retValue.Content.Headers.ContentType =
        new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
    return retValue;
}

Leave Your Comment

Liked this content?. Please spread the word :)