How do enable a .Net web-API to accept g-ziped posts

后端 未结 4 1548
别跟我提以往
别跟我提以往 2020-12-08 11:58

I have a fairly bog standard .net MVC 4 Web API application.

 public class LogsController : ApiController
{

    public HttpResponseMessage PostLog(List<         


        
4条回答
  •  无人及你
    2020-12-08 12:11

    try this

        public class DeCompressedContent : HttpContent
    {
        private HttpContent originalContent;
        private string encodingType;
    
        /// 
        /// 
        /// 
        /// 
        /// 
        public DeCompressedContent(HttpContent content, string encodingType)
        {
    
            if (content == null) throw new ArgumentNullException("content");
            if (string.IsNullOrWhiteSpace(encodingType)) throw new ArgumentNullException("encodingType");
    
            this.originalContent = content;
            this.encodingType = encodingType.ToLowerInvariant();
    
            if (!this.encodingType.Equals("gzip", StringComparison.CurrentCultureIgnoreCase) && !this.encodingType.Equals("deflate", StringComparison.CurrentCultureIgnoreCase))
            {
                throw new InvalidOperationException(string.Format("Encoding {0} is not supported. Only supports gzip or deflate encoding", this.encodingType));
            }
    
            foreach (KeyValuePair> header in originalContent.Headers)
            {
                this.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }
    
            this.Headers.ContentEncoding.Add(this.encodingType);
        }
    
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            var output = new MemoryStream();
    
            return this.originalContent
                .CopyToAsync(output).ContinueWith(task =>
                {
                    // go to start
                    output.Seek(0, SeekOrigin.Begin);
    
                    if (this.encodingType.Equals("gzip", StringComparison.CurrentCultureIgnoreCase))
                    {
                        using (var dec = new GZipStream(output, CompressionMode.Decompress))
                        {
                            dec.CopyTo(stream);
                        }
                    }
                    else
                    {
                        using (var def = new DeflateStream(output, CompressionMode.Decompress))
                        {
                            def.CopyTo(stream);
                        }
                    }
    
                    if (output != null)
                        output.Dispose();
                });
    
    
        }
    
        /// 
        /// 
        /// 
        /// 
        /// 
        protected override bool TryComputeLength(out long length)
        {
            length = -1;
    
            return (false);
        }
    }
    

提交回复
热议问题