我有以下控制器方法,它返回一个字节数组。
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;
}
我认为这是使用web api实现此功能的一种较旧方式。是否有更“现代”的版本?
例如,现在返回Task<IHttpActionResult>
首选方式?如果是这样,从上面返回字节数组的代码是什么?
答案 0 :(得分:2)
正如评论所指出的那样。我不认为有一种新方法可以做到这一点。但是,如果您想要返回IHttpActionResult
,则会有一个返回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);
}
答案 1 :(得分:1)
此外,如果有人需要,在AspNetCore WebApi2中返回二进制数据:
[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");
}