我正在尝试通过使用gZip压缩数据来减小请求大小。 我有以json格式发送的有效发布/投放请求,我想向他们发送一个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"
}