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

标签 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;
}

不起作用

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。因此,您需要设置 ContentNegotiatorFormatters 来格式化文件内容。由于您只想将原始 CSV 作为内容中的二进制数组返回(根据您的代码返回 HttpResponseMessage),那么您应该使用以下内容:

返回 this.ResponseMessage(result)

关于c# - 无法在 Web API 响应中序列化 ByteArraycontent 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738364/

相关文章:

c# - using 语句中使用的类型必须可隐式转换为 'System.IDisposable'

asp.net-web-api - 属性路由不适用于字典

c# - 使静态资源在 Azure Web 角色中可用

javascript - TypeScript、Knockout 和类

c# - .NET Web API 模型绑定(bind)前缀属性

c# - 属性路由值到模型/FromBody 参数

c# - 如何在 web api 中使用过滤器传递带有错误消息的状态

c# - 如何在 C# 中强制退出应用程序?

c# - : Must contain a numeric, 的正则表达式不包括 "SomeText1"

c# - Swagger-codegen c# : Missing client member of type byte[]