ServiceClient access compressed bytes

Quick question - is there a way with the ServiceClients to access the compressed response? I have a scenario where I would like to use the C# client to invoke my SS API requests with compression enabled and pass on the compressed bytes to another consumer.

When using a JsonServiceClient for example, the Get<string> does a great job at making everything transparent and returns the decompressed json string; however, there are some cases where I do not want to decompress.

Can the byte stream be accessed directly?

The Service Clients auto decompresses by default, you can try disabling the compression adding the Accept-Encoding headers manually to indicate to the server you still want a compressed response than read the results as a Stream or byte[], e.g:

string encodingUsed = null; 
var client = new JsonServiceClient(baseUrl) {
    DisableAutoCompression = true,
    RequestFilter = req => req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"),
    ResponseFilter = res => encodingUsed = res.Headers[HttpResponseHeader.ContentEncoding], 

using var stream = client.Get<Stream>(new MyRequest()); 

I’d only try this on a new JsonServiceClient instance (i.e. instead of a shared instance) since by disabling auto compression whilst still requesting compression puts the client in an invalid state where it wont be able to deserialize responses. I’d recommend instead using HttpWebRequest or HttpClient directly so you can better control the headers and response.

1 Like