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


This content was proof-read by Grammarly. You can Try Grammary for FREE

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;
}
%d bloggers like this: