我只想返回一个 .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;
}
不起作用
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);
}
错误 =>
The type "System.Net.Http.ByteArrayContent" can not be serialized.
Annotate it with the Attribut "DataContractAttribute"...
最佳答案
Content(HttpStatusCode.OK, result)
将返回一个 NegotiatedContentResult
。因此,您需要设置 ContentNegotiator
和 Formatters
来格式化文件内容。由于您只想将原始 CSV 作为内容中的二进制数组返回(根据您的代码返回 HttpResponseMessage
),那么您应该使用以下内容:
返回 this.ResponseMessage(result)
关于c# - 无法在 Web API 响应中序列化 ByteArraycontent 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738364/