danyolgiax
danyolgiax

Reputation: 13096

GZip response in API method with .NET Core 3.1

I need to GZip the object returned by a single API method in .NET Core 3.1 without enabling GZip globally.

I do it this way:

  [HttpGet]
    public async Task<IActionResult> Get()
    {

        var data =new  Foo();
        string serializedData = JsonConvert.SerializeObject(data);


        var bytes = Encoding.UTF8.GetBytes(serializedData);

        using (var msi = new MemoryStream(bytes))
        using (var mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
            {
                msi.CopyTo(gs);
            }

            Response.Headers.Add("Content-Encoding", "gzip");
            return Ok(mso.ToArray());
        }

    }

public class Foo
{
    public string Bar { get; set; }

}

When I test this method with browser I receive the following error:

GET http://localhost:5000/test net::ERR_CONTENT_DECODING_FAILED 200 (OK)

It seems the browser cannot decode the GZip content.

What I miss?

Upvotes: 1

Views: 3517

Answers (1)

MaxKlaxx
MaxKlaxx

Reputation: 763

Ok, I had to try a little bit (I don't have that much experience with .Net Core yet). But in the end it was quite simple: :)

[HttpGet]
public void Get()
{
  var data = new Foo();
  data.Bar = new string('a', 100000); // dummy content

  string serializedData = JsonConvert.SerializeObject(data);

  var bytes = Encoding.UTF8.GetBytes(serializedData);

  using (var msi = new MemoryStream(bytes))
  using (var mso = new MemoryStream())
  {
    using (var gs = new GZipStream(mso, CompressionMode.Compress))
    {
      msi.CopyTo(gs);
    }

    Response.Headers.Add("Content-Encoding", "gzip");
    Response.Body.WriteAsync(mso.ToArray());
  }

}

Upvotes: 3

Related Questions