2020-03-31

C#返回GZIP WEB请求时遇到的问题,做了两次压缩,正确的返回写法如下:

返回方式1:不用自己对返回内容做GZIP压缩,只用设置Response.Filter(推荐)
base.Context.Response.Clear();
base.Context.Response.ContentType = "Application/json";
base.Context.Response.Filter = new GZipStream(base.Context.Response.Filter, CompressionMode.Compress);
base.Context.Response.AppendHeader("Content-Encoding", "gzip");
base.Context.Response.Write(s);//s是原返回内容,不做压缩
base.Context.Response.End();

返回方式2:自己对返回内容做GZIP压缩,Response.Filter不用设置,但"Content-Encoding"仍需设为"gzip"
base.Context.Response.Clear();
base.Context.Response.ContentType = "Application/json";
base.Context.Response.AppendHeader("Content-Encoding", "gzip");
base.Context.Response.BinaryWrite(ret);//ret是经过GZIP压缩的byte数组
base.Context.Response.Flush();

你可能感兴趣的:(2020-03-31)