正确压缩webapi POST的方法

本文关键字:方法 POST webapi 压缩 | 更新日期: 2023-09-27 17:49:33

我有一个webform页面,它调用webapi方法来保存一些数据。我使用HttpClient来调用和执行webapi。

我尝试使用webAPI压缩发布一个巨大的xml到API。我基本上用了这两个网站作为参考:http://www.ronaldrosier.net/blog/2013/07/16/implement_compression_in_aspnet_web_api和http://benfoster.io/blog/aspnet-web-api-compression

API正在工作,它正在正确地触发处理程序。我正面临着一些问题,试图压缩和发布对象,从我的webforms在服务器端。

下面是我试过的代码:

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

当我执行上面的代码时,它没有抛出任何错误,在处理程序中,request.Content.ReadAsStringAsync()。结果一个巨大的'0'0'0'0'0'0 '0…

拜托,你们能告诉我我做错了什么吗?如何发送与XML的压缩对象到API正确?

谢谢

正确压缩webapi POST的方法

这是我想到的。由于您没有将请求设置为接受gzip编码,因此有可能使用HttpClientHandler。AutomaticDecompression,你可能会得到编码后的结果而不处理那个。但事实可能并非如此。无论如何,我可以确认这个例子是有效的。它是一个API控制器对另一个API控制器。在幕后,我设置WebApi接受gzip编码并在将其传递给控制器动作之前解压缩它;这是通过扩展DelegatingHandler类来实现的。我让IIS做响应压缩。我使用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();
}

你总是可以通过IIS使用HttpCompressionhttp://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>

那么HTTP客户端必须通过发送适当的HTTP接受编码头来发起压缩内容的通信。

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

下面是一个例子:http://benfoster.io/blog/aspnet-web-api-compression