将Zip文件作为响应在Web Api中返回

时间:2015-10-07 13:03:16

标签: c# asp.net-web-api zip

您好我已经创建了一个web api应用程序,我将返回响应作为文本文件。现在我想返回一个压缩文件以减小其大小

这是我的控制器代码

    public HttpResponseMessage Get(String parameter)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent(informationcontext.Records(parameter));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "sample"
        };


        return response;

}

任何人都能帮助我吗?

1 个答案:

答案 0 :(得分:1)

public HttpResponseMessage Post()
    {
        var ch = new ClientHandler();
        using (MemoryStream rms = new MemoryStream(Request.Content.ReadAsByteArrayAsync().Result))
        {
            using (GZipStream unzip = new GZipStream(rms, CompressionMode.Decompress))
            {
                ch.Requests = XElement.Load(unzip);
            }
        }

        MemoryStream outstream = new MemoryStream();
        try
        {
            ch.Start();
            using (GZipStream zip = new GZipStream(outstream, CompressionMode.Compress, true))
            {
                ch.Responses.Save(zip);
            }
        }
        catch (Exception ex)
        {
            XElement responses = new XElement("Responses");
            responses.Add(new XElement("Error", ex.Message));
            using (GZipStream zip = new GZipStream(outstream, CompressionMode.Compress, true))
            {
                responses.Save(zip);
            }
        }
        finally
        {
            ch.Dispose();
        }
        outstream.Position = 0;

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(outstream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }