2015-10-07 82 views
-2

嗨我創建了一個web api應用程序,並且我將響應作爲文本文件返回。現在我想回到一個壓縮文件,使其尺寸減小在Web Api中返回Zip文件作爲響應

這是我的控制器代碼

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; 

}

任何一個可以幫助我在這?

+0

http://stackoverflow.com/questions/22176147/how-to-send-zip-files-to-asp-net-webapi – mittmemo

+1

的可能重複看這個嗎? :http://stackoverflow.com/questions/14573915/using-asp-net-web-api-how-can-a-controller-return-a-collection-of-streamed-imag –

+0

可能重複的[我如何使用C#壓縮文件,不使用第三方API?](http://stackoverflow.com/questions/940582/how-do-i-zip-a-file-in-c-using-no-3rd-party -蜜蜂) – Liam

回答

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; 
    } 
相關問題