[英]How to get response message from web api?
I have the following web controller: 我有以下Web控制器:
List<string> output = new List<string>();
output.Add("line1");
output.Add("line2");
output.Add("line3");
output.Add("line4");
using (var memorystream = new MemoryStream())
{
using (var archive = new ZipArchive(memorystream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry("entry1");
using (var entryStream = fileInArchive.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
output.ForEach(streamWriter.WriteLine);
}
}
memorystream.Seek(0, SeekOrigin.Begin);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memorystream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return result;
}
On the receiving end i have ac# web form that access the controller this way: 在接收端,我有一个以这种方式访问控制器的ac #web表单:
var responsebody = response.Content.ReadAsByteArrayAsync().Result;
string filename = "test.zip";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AppendHeader(
"content-disposition", string.Format("attachment; filename={0}", filename));
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.BinaryWrite(responsebody.ToArray());
But I just get an array of bytes in the reponsebody var. 但我只是在reponsebody var中得到一个字节数组。 How can I convert this back to the original type, which is a ziparchive, or just another binary file to have it more generic?
我如何将其转换回原始类型,这是一个ziparchive,或只是另一个二进制文件,使其更通用?
How can I convert this back to the original type, which is a
ZipArchive
?如何将其转换回原始类型,即
ZipArchive
?
You sent back the byte[]
as the response. 您发送了
byte[]
作为响应。 That means, that on the receiving end, you'll have to exactly reverse that same process. 这意味着,在接收端,你必须完全扭转相同的过程。 Meaning, you take the byte array and put it into a
ZipArchive
, and start reading: 意思是,你把字节数组放到
ZipArchive
,然后开始阅读:
var bytes = await response.Content.ReadAsByteArrayAsync();
using (var zippedBytesStream = new MemoryStream(bytes))
using (var archive = new ZipArchive(zippedBytesStream, ZipArchiveMode.Read, true))
{
foreach (ZipEntry entry in archive.Entries)
{
// Do stuff with entry.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.