4

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?

1
  • 1
    I do not believe there is any new way to handle this. Web API 2 has not changed. I see there is no await inside your method, for this reason you should avoid making it async, just use HttpResponseMessage as return type. Commented May 13, 2017 at 11:57

2 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

5

Also, to return binary data in AspNetCore WebApi2 if anyone needs it:

[Route("api/v1/export/excel")]
[HttpGet]
public IActionResult GetAsExcel()
{
    var exportStream = new MemoryStream();
    _exportService.ExportAllToExcel(exportStream);
    // Rewind the stream before we send it.
    exportStream.Position = 0;
    return new FileStreamResult(exportStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.