类型ByteArraycontent无法在web api响应中序列化

时间:2016-04-20 08:43:12

标签: c# asp.net-web-api asp.net-web-api2

我只想返回一个.csv文件。

适用于 HttpResponseMessage ,但不适用于 IHttpActionResult

为什么?

WORKS

public async Task<HttpResponseMessage> ExportLeads()
{
    byte[] bytes = new byte[2];
    var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "test.csv" };
    return result;
}

不工作

public async Task<IHttpActionResult> ExportLeads()
{
    byte[] bytes = new byte[2];
    var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "test.csv" };
    return Content(HttpStatusCode.OK, result);
}

错误 =&gt;

The type "System.Net.Http.ByteArrayContent" can not be serialized.
Annotate it with the Attribut "DataContractAttribute"...

1 个答案:

答案 0 :(得分:4)

Content(HttpStatusCode.OK, result)将返回NegotiatedContentResult。因此,您需要设置ContentNegotiatorFormatters来格式化文件内容。由于您只想将原始CSV作为二进制数组返回到内容中(根据您的代码返回HttpResponseMessage),您应该使用以下内容:

return this.ResponseMessage(result)