使用 web api 返回二进制数据

Joh*_*ore 2 asp.net-web-api asp.net-web-api2

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

    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;
    }
Run Code Online (Sandbox Code Playgroud)

我认为这是使用 web api 实现此功能的较旧方法。有没有更“现代”的版本?

例如,现在返回一个Task<IHttpActionResult>首选方式吗?如果是这样,从上面返回字节数组的代码是什么?

pec*_*eco 5

正如评论指出的那样。我不认为有新的方法可以做到这一点。但是,如果您想返回一个IHttpActionResult,则有一个返回 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);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

另外,如果有人需要的话,要在 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");
}
Run Code Online (Sandbox Code Playgroud)