We are using gZip to compress/decompress of the response received from the web api. Below is our implementation.
[Route("Location")]
[HttpGet]
[DeflateCompression]
public async Task<IEnumerable<DisplayLocation>> GetLocation(string searchTerm = null, string impersonationUserId = null)
{
IEnumerable<DisplayLocation> locations= await DisplayLocationServer.GetLocation(searchTerm, WebUser);
return locations;
}
and OnActionExecuted method Added compression logic
public override void OnActionExecuted(HttpActionExecutedContext actContext)
{
IEnumerable<string> acceptedEncoding =
GetAcceptedEncodingFromHeader(actContext.Request);
if(acceptedEncoding != null && acceptedEncoding.Contains("deflate"))
{
HttpContent content = actContext.Response.Content;
byte[] bytes = content?.ReadAsByteArrayAsync().Result;
byte[] zlibbedContent = bytes == null ? new byte[0] :
CompressionHelper.DeflateByte(bytes);
actContext.Response.Content = new ByteArrayContent(zlibbedContent);
actContext.Response.Content.Headers.Remove("Content-Type");
actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
actContext.Response.Content.Headers.Add("Content-Type", "application/json");
}
base.OnActionExecuted(actContext);
}
private IEnumerable<string> GetAcceptedEncodingFromHeader(HttpRequestMessage request)
{
IEnumerable<string> headerValues = new List<string>();
if(request.Headers != null)
{
request.Headers.TryGetValues("Accept-Encoding", out headerValues);
}
return headerValues;
}
Till this compression logic it works fine. However, when we try to return the response from api side to UI it gives the error.
We are using swagger to consume web api which auto generates code and from that code request/response done. The response will be send to UI from auto generated code.
Below is the auto generated code where content will be deserialize returned from actual api method.
String _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<DisplayLocation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
As the content is in zipped format, the response is not getting deserialized properly.
So my question is how can we zip the content/response properly which will work with this code ?
Also, we cannot do changes in auto generated code as it can be auto generated again in future so manual changes will be lost.
In short, we are trying to get the compressed content on UI side and will write decompress logic there. But because of swagger/auto generated code it is failing at that point only.
Any help on this appreciated !