HttpResponseMessage
用于Web服务方法,我收到 InvalidDataContractException 。
public HttpResponseMessage GetData()
{
var fileContent = Encoding.UTF8.GetBytes(
@"{
""fruit"":""apple"",
""taste"":""yummy""
}"
);
MemoryStream zipContent = new MemoryStream();
ZipArchive archive = new ZipArchive(zipContent, ZipArchiveMode.Create);
Zip_AddEntry("file1.json", fileContent, archive);
Zip_AddEntry("file2.json", fileContent, archive); //second file (same content)
zipContent.Position = 0;
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(zipContent);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.Add("x-filename", "GenInst_FMS.zip");
response.Content.Headers.ContentLength = zipContent.Length;
return response;
}
private static void Zip_AddEntry(string fileName, byte[] fileContent, ZipArchive archive)
{
var entry = archive.CreateEntry(fileName);
using (var stream = entry.Open())
stream.Write(fileContent, 0, fileContent.Length);
}
例外是:
System.Runtime.Serialization.InvalidDataContractException, System.Runtime.Serialization,Version = 4.0.0.0,Culture = neutral, PublicKeyToken = b77a5c561934e089类型 'System.Net.Http.StreamContent'无法序列化。考虑标记 它与DataContractAttribute属性,并标记其所有 要使用DataMemberAttribute属性序列化的成员。 如果类型是集合,请考虑使用 CollectionDataContractAttribute。请参阅Microsoft .NET Framework 其他支持类型的文档。