How to Return binary file from controller in ASP.NET Web API?

82 Points
31 Posts

I'm trying to return binary result from api action controller as:

public IHttpActionResult RecieveUserImage([FromUri]RecieveUserImageRequest recieveUserImageRequest)
    byte[] ImageByte = { };

    System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream(ImageByte);
    System.Web.Mvc.FileStreamResult FileStreamResult = new System.Web.Mvc.FileStreamResult(oMemoryStream, "image/jpeg");

    return FileStreamResult;

But getting compile time error:

Views: 394
Total Answered: 1
Total Marked As Answer: 0
Posted On: 22-Feb-2020 01:14

Share:   fb twitter linkedin
Rahul Maurya
Rahul M...
1232 Points
216 Posts

We can using simple HttpResponseMessage by suing content stream to pass to content:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage RecieveUserImage()
    byte[] ImageByte = { };
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream(ImageByte);
    result.Content = new StreamContent(oMemoryStream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return result;
Posted On: 22-Feb-2020 06:02
 Log In to Chat