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

Priya
Priya
Member
70 Points
30 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: 162
Total Answered: 1
Total Marked As Answer: 0
Posted On: 22-Feb-2020 01:14

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Moderator
1186 Points
213 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