Returning binary data with web api

2019-08-11 08:48发布

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?

2条回答
Rolldiameter
2楼-- · 2019-08-11 09:12

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);
}
查看更多
迷人小祖宗
3楼-- · 2019-08-11 09:16

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");
}
查看更多
登录 后发表回答