所以我把它用在服務器端簡單的中間件並沒有太多的工作就上班客戶端。我使用WebAPIContrib github項目中的CompressedContent.cs,正如Rex在他的回答中提出的建議,並提出瞭如下所示的請求。整個拋出異常,如果不是好的,因爲我正在使用Polly包裹我的請求與重試和等待策略。
客戶端:
using (var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json"))
using (var compressedContent = new CompressedContent(httpContent, "gzip"))
using (HttpResponseMessage response = client.PostAsync("Controller/Action", compressedContent).Result)
{
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception(string.Format("Invalid responsecode for http request response {0}: {1}", response.StatusCode, response.ReasonPhrase));
}
}
然後在服務器端我創建了一個簡單的中間件的那個包裹與Gzip已流請求體流,我敢肯定你需要的應用程序之前,把中間件。 UseMvc()在配置功能中(我仍然使用ASPcore 1啓動樣式)。
public class GzipRequestMiddleware
{
private readonly RequestDelegate next;
private const string ContentEncodingHeader = "Content-Encoding";
private const string ContentEncodingGzip = "gzip";
private const string ContentEncodingDeflate = "deflate";
public GzipRequestMiddleware(RequestDelegate next)
{
this.next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains(ContentEncodingHeader) && (context.Request.Headers[ContentEncodingHeader] == ContentEncodingGzip || context.Request.Headers[ContentEncodingHeader] == ContentEncodingDeflate))
{
var contentEncoding = context.Request.Headers[ContentEncodingHeader];
var decompressor = contentEncoding == ContentEncodingGzip ? (Stream)new GZipStream(context.Request.Body, CompressionMode.Decompress, true) : (Stream)new DeflateStream(context.Request.Body, CompressionMode.Decompress, true);
context.Request.Body = decompressor;
}
await next(context);
}
}
一個參考MSDN鏈接將是完美的 –
https://blogs.msdn.microsoft.com/dotnet/2013/06/06/portable-compression-and-httpclient-working-together/ – Rex
也許我缺少一些東西,但看起來它只會處理響應解壓縮而不是請求壓縮,對吧? – Theyouthis