使用HttpClient将请求压缩到asp.net core 2站点的最佳方法是什么? [英] What is the best way to compress a request to asp.net core 2 site using HttpClient?

查看:131
本文介绍了使用HttpClient将请求压缩到asp.net core 2站点的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发送可能很大的请求(〜1Mb),当我发出请求以及asp.net核心记录它正在处理请求时,看到很大的延迟.我想我可以通过使用gzip将请求压缩为asp来减少时间.

I am sending request that can be significantly big(~1Mb) and I am seeing a large delay betweeen when I make the request and when asp.net core logs that it is handling the request. I think I can cut down this time by compressing the request to asp using gzip.

下面是我在不压缩的情况下进行请求的相当直接的方法.在客户端请求端实现Gzip请求压缩的正确方法是什么,一旦在客户端上实现它,我需要在服务器端做什么?

Below is the fairly straight forward way that I am making requests without compression. What is the proper way to implement Gzip request compression on the client requesting side, and once I implement it on the client, what do I need to do for the server side?

using (HttpResponseMessage response = client.PostAsync("Controller/Action", httpContent).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));
    }
}

推荐答案

因此,我可以在服务器端使用简单的中间件来工作,而在客户端却不需要太多的工作.我使用了来自WebAPIContrib的 CompressedContent.cs ,就像雷克斯(Rex)在他的回答评论中所建议的那样,并发出了如下所示的请求.整个throw-exception-if-not-OK的原因是因为我使用的是将Polly包裹在带有重试和等待策略的请求上.

So I got it to work with simple middleware on the server side and not too much work on the client side. I used CompressedContent.cs from WebAPIContrib, as Rex suggested in the comments of his answer, and made the request as shown below. The whole throw-exception-if-not-OK is because I am using Polly wrapped around my request with a Retry and wait policy.

客户端:

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流包装在一起.要使用它,您需要在Startup.csConfigure方法中对app.UseMvc();的调用之前在app.UseMiddleware<GzipRequestMiddleware>(); 之前添加行.

Then on the server side I created a simple piece of middleware that wraps the request body stream with the Gzip stream. To use it, you need to add the line app.UseMiddleware<GzipRequestMiddleware>(); before the call to app.UseMvc(); in your Startup.cs's Configure method.

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

这篇关于使用HttpClient将请求压缩到asp.net core 2站点的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆