问题描述
我有以下返回字节数组的控制器方法.
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;
}
我认为这是使用Web API实现此功能的较旧方法.还有更现代"的版本吗?
I think this is an older way of implementing this functionality with web api. Is there a more "modern" version?
例如,现在首选返回Task<IHttpActionResult>
吗?如果是这样,从上面返回字节数组的代码是什么?
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?
推荐答案
正如评论所指出的.我认为没有新的方法可以做到这一点.但是,如果您想返回一个IHttpActionResult
,则有一个基本方法返回一个ResponseMessageResult
:
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);
}
这篇关于使用Web API返回二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!