Returning binary data with web api

时光总嘲笑我的痴心妄想 提交于 2020-01-05 11:56:21

问题


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:


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);
}



回答2:


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");
}


来源:https://stackoverflow.com/questions/43946573/returning-binary-data-with-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!