public class CompressContent : HttpContent { _encodingType; private readonly HttpContent _originalContent; ) { _originalContent = content; _encodingType = encodingType.ToLowerInvariant(); Headers.ContentEncoding.Add(encodingType); } TryComputeLength(out long length) { length = -1; return false; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { Stream compressStream = null; switch (_encodingType) { : compressStream = new GZipStream(stream, CompressionMode.Compress, true); break; : compressStream = new DeflateStream(stream, CompressionMode.Compress, true); break; default: compressStream = stream; break; } return _originalContent.CopyToAsync(compressStream).ContinueWith(tsk => { if (compressStream != null) { compressStream.Dispose(); } }); } }
重写过滤器特性
public class CompressContentAttribute : ActionFilterAttribute { OnActionExecuted(HttpActionExecutedContext context) { var acceptedEncoding = context.Response.RequestMessage.Headers.AcceptEncoding.First().Value; , StringComparison.InvariantCultureIgnoreCase) && !acceptedEncoding.Equals(, StringComparison.InvariantCultureIgnoreCase)) {