Exemple #1
0
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="content">An existing <see cref="Windows.Web.Http.IHttpContent"/> implementation to be compressed.</param>
        /// <param name="encodingType">The type of compression to use. Supported values are 'gzip' and 'deflate'.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="content"/> or <paramref name="encodingType"/> are null.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown if <paramref name="encodingType"/> is not 'gzip' or 'deflate'.</exception>
        public CompressedWebContent(IHttpContent content, string encodingType)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (encodingType == null)
            {
                throw new ArgumentNullException("encodingType");
            }

            this.encodingType = encodingType;

            originalContent = content;
            if (String.Compare(this.encodingType, "gzip", true) != 0 && String.Compare(this.encodingType, "deflate", true) != 0)
            {
                throw new InvalidOperationException(string.Format("Encoding '{0}' is not supported. Only supports gzip or deflate encoding.", this.encodingType));
            }

            headers = new HttpContentHeaderCollection();
            originalContent.CopyHeadersTo(this);

            headers.ContentEncoding.Add(new HttpContentCodingHeaderValue(encodingType));
            headers.ContentLength = null;
        }
        private static async Task <IHttpContent> GetCompressedContent(IHttpContent originalContent)
        {
            var ms = new System.IO.MemoryStream();

            try
            {
                await CompressOriginalContentStream(originalContent, ms).ConfigureAwait(false);

                ms.Seek(0, System.IO.SeekOrigin.Begin);

                var compressedContent = new Windows.Web.Http.HttpStreamContent(ms.AsInputStream());
                originalContent.CopyHeadersTo(compressedContent);
                compressedContent.Headers.ContentEncoding.Clear();
                compressedContent.Headers.ContentEncoding.Add(new Windows.Web.Http.Headers.HttpContentCodingHeaderValue("gzip"));
                compressedContent.Headers.ContentLength = (ulong)ms.Length;

                originalContent.Dispose();

                return(compressedContent);
            }
            catch
            {
                ms?.Dispose();
                throw;
            }
        }