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
source share