Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning binary data with web api

I have the following controller method which returns a byte array.

    public async Task<HttpResponseMessage> Get()
    {
        var model = new byte[] { 1, 2, 3 };

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(new MemoryStream(model));
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

I think this is an older way of implementing this functionality with web api. Is there a more "modern" version?

For example, is returning a Task<IHttpActionResult> the preferred way now? And if so, what would be the code to return the byte array from above?

like image 595
John Livermore Avatar asked Nov 07 '25 23:11

John Livermore


1 Answers

As the comment pointed out. I dont think there is a new way to do this. But if you would like to return an IHttpActionResult instead, there is a base method that returns a ResponseMessageResult:

public IHttpActionResult Get()
{
    var model = new byte[] { 1, 2, 3 };

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StreamContent(new MemoryStream(model))
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return ResponseMessage(result);
}
like image 72
peco Avatar answered Nov 12 '25 17:11

peco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!