简体   繁体   中英

How to get response message from web api?

I have the following web controller:

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:

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. How can I convert this back to the original type, which is a ziparchive, or just another binary file to have it more generic?

How can I convert this back to the original type, which is a ZipArchive ?

You sent back the byte[] as the response. 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:

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM