使用 Web API 返回二进制数据



我有以下控制器方法返回一个字节数组。

    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>是首选方式吗? 如果是这样,从上面返回字节数组的代码是什么?

正如评论指出的那样。我认为没有新的方法可以做到这一点。但是,如果您想返回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);
}

另外,如果有人需要,要在 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");
}

最新更新