无法在Web API响应中序列化ByteArraycontent类型

Hel*_*rld 3 c# asp.net-web-api asp.net-web-api2

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

它适用于HttpResponseMessage,但不适用于IHttpActionResult

为什么?

作品

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

不起作用

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

错误 =>

The type "System.Net.Http.ByteArrayContent" can not be serialized.
Annotate it with the Attribut "DataContractAttribute"...
Run Code Online (Sandbox Code Playgroud)

str*_*t01 5

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

return this.ResponseMessage(result)