如何压缩HttpClient帖子并在web api中接收数据

时间:2015-11-16 11:26:57

标签: c# asp.net-mvc-4 http asp.net-web-api

我有以下web api客户端,它使用json和gzip将数据发送到服务器:

    public void Remote_Push(BlockList Blocks)
    {
        // Pushes pending records to the remote server
        using (var Client = new HttpClient())
        {
            Client.BaseAddress = new Uri(Context.ServerUrl);
            Client.DefaultRequestHeaders.Accept.Clear();
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var Content = JsonCompress(Blocks);
            var T1 = Client.PostAsync("SyncPush/", Content); T1.Wait();
            T1.Result.EnsureSuccess();
        }
    }

    private static ByteArrayContent JsonCompress(object Data)
    {
        // Compress given data using gzip 
        var Bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Data));
        using (var Stream = new MemoryStream())
        {
            using (var Zipper = new GZipStream(Stream, CompressionMode.Compress, true)) Zipper.Write(Bytes, 0, Bytes.Length);
            var Content = new ByteArrayContent(Stream.ToArray());
            Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            Content.Headers.ContentEncoding.Add("gzip");
            return Content;
        }
    }

在服务器上,我在web api控制器中创建了以下操作:

    [HttpPost]
    public void SyncPush([FromBody]BlockList Blocks)
    {
        var Context = SyncCreateContext();
        var Sync = new Processor(Context);
        Sync.ServerPush(Blocks);
    }

以前,我在客户端上使用过PostAsJsonAsync并且工作正常。

现在,我已切换到ByteArrayContentgzip并且不再有效,Blocks在服务器上始终为null。 我在这里错过了什么,有什么不对或可能是问题?

1 个答案:

答案 0 :(得分:1)

以下是一个示例控制台应用程序,用于执行您要执行的操作。

      /*using System;
      using System.IO;
      using System.IO.Compression;
      using System.Net.Http;
      using System.Net.Http.Headers;
      using System.Text;
      using Newtonsoft.Json;
      using WebApi.Models;*/

 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Press any key to POST");
        Console.ReadLine();
        RemotePush(new BlockList());
        Console.ReadLine();
    }

    public static async void RemotePush(BlockList blocks)
    {
        try
        {
            using (var client = new HttpClient())
            {
                try
                {
                    Console.WriteLine("Please wait.");
                    client.BaseAddress = new Uri("http://localhost:52521/Home/"); 
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var content = JsonCompress(blocks);
                    var response = await client.PostAsync("SyncPush/", content);
                    using (var stream = await response.Content.ReadAsStreamAsync())
                    {
                        using (var streamReader = new StreamReader(stream))
                        {
                            Console.WriteLine(streamReader.ReadToEnd());
                        }
                    }
                    Console.WriteLine("Done.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private static MultipartFormDataContent JsonCompress(object data)
    {
        var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
        var stream = new MemoryStream();
        using (var zipper = new GZipStream(stream, CompressionMode.Compress, true))
        {
            zipper.Write(bytes, 0, bytes.Length);
        }
        MultipartFormDataContent multipartContent = new MultipartFormDataContent();
        multipartContent.Add(new StreamContent(stream), "gzipContent");
        return multipartContent;
    }
}

我的控制器是这样的。

    [System.Web.Mvc.HttpPost]
    public JsonResult SyncPush(BlockList content)
    {
        try
        {
            if (content != null)
            {
                return Json("success", JsonRequestBehavior.AllowGet);
            }
            return Json("failed due to null", JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("failed " + ex.Message, JsonRequestBehavior.AllowGet);
        }
    }