The correct way to compress webapi POST

I have a web form page that calls the webapi method to save some data. I am using HttpClient to make a call and execute webapi.

I tried using webAPI compression to publish huge xml in the API. I mainly used these two sites as a link: http://www.ronaldrosier.net/blog/2013/07/16/implement_compression_in_aspnet_web_api and http://benfoster.io/blog/aspnet-web-api-compression

The API works, it correctly starts the handler. I am encountering some problems trying to compress and publish an object from my server side web forms.

Here is the code I tried:

bool Error = false; //Object to post. Just an example... PostParam testParam = new PostParam() { inputXML = "<xml>HUGE XML</xml>", ID = 123 }; try { using (var client = new HttpClient()) { using (var memStream = new MemoryStream()) { var data = new DataContractJsonSerializer(typeof(PostParam)); data.WriteObject(memStream, testParam); memStream.Position = 0; var contentToPost = new StreamContent(this.Compress(memStream)); contentToPost.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); contentToPost.Headers.Add("Content-Encoding", "gzip"); var response = client.PostAsync(new Uri("http://myapi/SAVE"), contentToPost).Result; var dataReceived = response.EnsureSuccessStatusCode(); dynamic results; if (dataReceived.IsSuccessStatusCode) { results = JsonConvert.DeserializeObject<dynamic>(dataReceived.Content.ReadAsStringAsync().Result); try { this.Error = results.errors.Count == 0; } catch { } } } } } catch { this.Error = true; } //Compress stream private MemoryStream Compress(MemoryStream ms) { byte[] buffer = new byte[ms.Length]; // Use the newly created memory stream for the compressed data. GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); // Close the stream. compressedzipStream.Close(); MemoryStream ms1 = new MemoryStream(buffer); return ms1; } 

When I execute the above code, it does not throw any error in the request.Content.ReadAsStringAsync () handler either. result a huge \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 ...

Please, could you guys show me what I'm doing wrong? How to properly send a compressed object with XML to the API?

thanks

+6
source share
2 answers

Here is what I came up with. It is possible that since you are not setting up a request to accept the gzip encoding using the HttpClientHandler.AutomaticDecompression , you can get back-coded results and not take into account the processing of this. Perhaps this is not so. In any case, I can confirm that this example works. This is one API controller for another. Behind the scenes, I have a WebApi setup to accept gzip encoding and unpack it before passing it to the controller; this is done by extending the DelegatingHandler class. I will allow IIS to compress the response. I am using WebApi 2.

 public async Task<IHttpActionResult> Get() { List<PersonModel> people = new List<PersonModel> { new PersonModel { FirstName = "Test", LastName = "One", Age = 25 }, new PersonModel { FirstName = "Test", LastName = "Two", Age = 45 } }; using (HttpClientHandler handler = new HttpClientHandler()) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (HttpClient client = new HttpClient(handler, false)) { string json = JsonConvert.SerializeObject(people); byte[] jsonBytes = Encoding.UTF8.GetBytes(json); MemoryStream ms = new MemoryStream(); using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true)) { gzip.Write(jsonBytes, 0, jsonBytes.Length); } ms.Position = 0; StreamContent content = new StreamContent(ms); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); content.Headers.ContentEncoding.Add("gzip"); HttpResponseMessage response = await client.PostAsync("http://localhost:54425/api/Gzipping", content); IEnumerable<PersonModel> results = await response.Content.ReadAsAsync<IEnumerable<PersonModel>>(); Debug.WriteLine(String.Join(", ", results)); } } return Ok(); } 
+14
source

You can always use HttpCompression through IIS http://www.iis.net/configreference/system.webserver/httpcompression

 <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files"> <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" /> <dynamicTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/javascript" enabled="true" /> <add mimeType="*/*" enabled="false" /> </dynamicTypes> <staticTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/javascript" enabled="true" /> <add mimeType="*/*" enabled="false" /> </staticTypes> </httpCompression> 

Then, the HTTP client must initiate a link for the compressed content by sending the appropriate HTTP-Accept-encoding header.

 httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 

Here is an example: http://benfoster.io/blog/aspnet-web-api-compression

+2
source

Source: https://habr.com/ru/post/987437/


All Articles