正确的方法来从.NET HttpClient压缩PUT内容?

时间:2018-05-17 16:20:56

标签: c# .net dotnet-httpclient

我还没有找到有关使用.NET HttpClient发送压缩PUT的详细信息。我有一个可压缩字节数组的Gzip压缩类,但我不确定下面的内容是否是正确的做法:

    public HttpRequestMessage GetHttpPutRequestMessage(string uri, string dataToPut, string username, string password)
    {
        var request = SetupHttpRequestMessage(HttpMethod.Put, uri, username, password);

        byte[] bytesToSend = _useCompression ? 
            _compressionService.Compress(Encoding.ASCII.GetBytes(dataToPut)) : Encoding.ASCII.GetBytes(dataToPut);

        request.Content = new ByteArrayContent(bytesToSend, 0, bytesToSend.Length);

        return request;
    }

    private HttpRequestMessage SetupHttpRequestMessage(HttpMethod method, string uri, string username, string password)
    {
        var request = new HttpRequestMessage(method, uri);
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
        request.Headers.Authorization =
            new AuthenticationHeaderValue(
                "Basic", Convert.ToBase64String(byteArray));

        request.Headers.ExpectContinue = false;

        if (_usingEmulator)
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType));

        if (_useCompression)
        {
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
        }

        return request;
    }

压缩类非常简单。压缩方法如下:

    public byte[] Compress(byte[] data)
    {
        using (var compressedStream = new MemoryStream())
        {
            using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
            {
                zipStream.Write(data, 0, data.Length);
                zipStream.Close();
                return compressedStream.ToArray();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以在.net core上尝试以下方法。

'services.AddResponseCompression(options =>
            {
                options.Providers.Add<BrotliCompressionProvider>();
                options.Providers.Add<GzipCompressionProvider>();
                options.EnableForHttps = true;
            });'

            'services.Configure<BrotliCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });'

            'services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });'