首页 > 解决方案 > 如何在 post/put 请求中读取压缩数据(API 端)

问题描述

我正在尝试通过使用 gZip 压缩数据来减小请求大小。我有作为 json 发送的工作 post/put 请求,我想向他们发送 gZip。

对于服务器到客户端的方式,我得到了它:

services.AddResponseCompression(o =>
{
    o.Providers.Add<GzipCompressionProvider>();
});
app.UseResponseCompression();

对于客户端到服务器的方式,我无法让它工作。我添加了这种压缩方法:

private static byte[] Zip(string str)
{
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream())
    {
        using (var gs = new GZipStream(mso, CompressionMode.Compress))
        {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}


private static void CopyTo(Stream src, Stream dest)
{
    var bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) dest.Write(bytes, 0, cnt);
}

我这样发送请求:

internal static async Task<object> PostAsync(string request, object value, string token = null)
{

    //Create the http client to send the request
    using (var client = new HttpClient())
    {
        //Add the token from the user
        if (!string.IsNullOrEmpty(token))
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));

        var serializedValues = SerializeSplitter(value);
        var output = new List<bool>();
        //Wait for the server response
        foreach (var serializedValue in serializedValues)
        {

            var response = await client
                .PostAsync(Host + request, new StringContent(Encoding.UTF8.GetString(Zip(serializedValue)), Encoding.UTF8, "application/json"))
                .ConfigureAwait(false);
            output.Add(response.IsSuccessStatusCode);
        }

        //TODO Add error manager

        return output.All(i => i);
    }
}

当我发送请求时,我得到一个 BadRequest 400 :

{
    "errors": {
        "": [
            "Unexpected character encountered while parsing value: \u001f. Path '', line 0, position 0."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HLN405BDHU0T:00000001"
}

标签: c#apigzip

解决方案


推荐阅读