/// <summary>
        /// Handles the BeginRequest event of the context control.
        /// </summary>
        /// <param name="sender">The source of the event</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data</param>
        private void PreRequestHandlerExecute(object sender, EventArgs e)
        {
            if (!_configuration.IsCompressionEnabled())
            {
                return;
            }

            HttpContext  context   = ((HttpApplication)sender).Context;
            HttpRequest  request   = context.Request;
            HttpResponse response  = context.Response;
            string       mediaType = response.ContentType;

            if (request.HttpMethod == "GET" && response.StatusCode == 200 &&
                _compressionManager.IsSupportedMediaType(mediaType))
            {
                context.Items["originalResponseFilter"] = response.Filter;

                string acceptEncoding = request.Headers["Accept-Encoding"];

                ICompressor compressor = _compressionManager.CreateCompressor(acceptEncoding);
                response.Filter = compressor.Compress(response.Filter);
                compressor.AppendHttpHeaders((key, value) =>
                {
                    response.Headers[key] = value;
                });
            }
        }
        /// <summary>
        /// Override to compress the content that is generated by an action method
        /// </summary>
        /// <param name="filterContext">Filter context</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!_configuration.IsCompressionEnabled())
            {
                return;
            }

            HttpContextBase  context   = filterContext.HttpContext;
            HttpRequestBase  request   = context.Request;
            HttpResponseBase response  = context.Response;
            string           mediaType = response.ContentType;

            if (response.Filter != null && _compressionManager.IsSupportedMediaType(mediaType))
            {
                context.Items["originalResponseFilter"] = response.Filter;

                string acceptEncoding = request.Headers["Accept-Encoding"];

                ICompressor compressor = _compressionManager.CreateCompressor(acceptEncoding);
                response.Filter = compressor.Compress(response.Filter);
                compressor.AppendHttpHeaders((key, value) =>
                {
                    response.Headers[key] = value;
                });
            }
        }
        public void OnLoad(EventArgs e)
        {
            if (DisableCompression)
            {
                return;
            }

            HttpContext  context   = HttpContext.Current;
            HttpRequest  request   = context.Request;
            HttpResponse response  = context.Response;
            string       mediaType = response.ContentType;

            if (_compressionManager.IsSupportedMediaType(mediaType))
            {
                context.Items["originalResponseFilter"] = response.Filter;

                string acceptEncoding = request.Headers["Accept-Encoding"];

                ICompressor compressor = _compressionManager.CreateCompressor(acceptEncoding);
                response.Filter = compressor.Compress(response.Filter);
                compressor.AppendHttpHeaders((key, value) =>
                {
                    response.Headers[key] = value;
                });
            }
        }
Example #4
0
        private Stream GetOutputStream()
        {
            if (_outputStreamInitializedFlag.Set())
            {
                if (HttpHeadersHelpers.IsEncodedContent(_response.Headers))
                {
                    _outputStream = _originalStream;
                }
                else
                {
                    _compressor   = _compressionManager.CreateCompressor(_acceptEncoding);
                    _outputStream = _compressor.Compress(_originalStream);
                }
            }

            return(_outputStream);
        }
Example #5
0
        public async Task Invoke(HttpContext context)
        {
            bool useMinification = _options.IsMinificationEnabled() && _minificationManagers.Count > 0;
            bool useCompression  = _options.IsCompressionEnabled() && _compressionManager != null;

            if (!useMinification && !useCompression)
            {
                await _next.Invoke(context);

                return;
            }

            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            using (var cachedStream = new MemoryStream())
            {
                Stream originalStream = response.Body;
                response.Body = cachedStream;

                try
                {
                    await _next.Invoke(context);
                }
                catch (Exception)
                {
                    response.Body = originalStream;
                    cachedStream.SetLength(0);

                    throw;
                }

                byte[] cachedBytes     = cachedStream.ToArray();
                int    cachedByteCount = cachedBytes.Length;
                bool   isProcessed     = false;

                response.Body = originalStream;
                cachedStream.SetLength(0);

                if (request.Method == "GET" && response.StatusCode == 200 &&
                    _options.IsAllowableResponseSize(cachedByteCount))
                {
                    string   contentType = response.ContentType;
                    string   mediaType   = null;
                    Encoding encoding    = null;

                    if (contentType != null)
                    {
                        MediaTypeHeaderValue mediaTypeHeader;

                        if (MediaTypeHeaderValue.TryParse(contentType, out mediaTypeHeader))
                        {
                            mediaType = mediaTypeHeader.MediaType.ToLowerInvariant();
                            encoding  = mediaTypeHeader.Encoding;
                        }
                    }

                    encoding = encoding ?? Encoding.GetEncoding(0);

                    string      currentUrl  = request.Path.Value;
                    QueryString queryString = request.QueryString;
                    if (queryString.HasValue)
                    {
                        currentUrl += queryString.Value;
                    }

                    string            content          = encoding.GetString(cachedBytes);
                    string            processedContent = content;
                    IHeaderDictionary responseHeaders  = response.Headers;
                    bool isEncodedContent = responseHeaders.IsEncodedContent();
                    Action <string, string> appendHttpHeader = (key, value) =>
                    {
                        responseHeaders.Append(key, new StringValues(value));
                    };

                    if (useMinification)
                    {
                        foreach (IMarkupMinificationManager minificationManager in _minificationManagers)
                        {
                            if (mediaType != null && minificationManager.IsSupportedMediaType(mediaType) &&
                                minificationManager.IsProcessablePage(currentUrl))
                            {
                                if (isEncodedContent)
                                {
                                    throw new InvalidOperationException(
                                              string.Format(
                                                  AspNetCommonStrings.MarkupMinificationIsNotApplicableToEncodedContent,
                                                  responseHeaders["Content-Encoding"]
                                                  )
                                              );
                                }

                                IMarkupMinifier minifier = minificationManager.CreateMinifier();

                                MarkupMinificationResult minificationResult = minifier.Minify(processedContent, currentUrl, encoding, false);
                                if (minificationResult.Errors.Count == 0)
                                {
                                    processedContent = minificationResult.MinifiedContent;
                                    if (_options.IsPoweredByHttpHeadersEnabled())
                                    {
                                        minificationManager.AppendPoweredByHttpHeader(appendHttpHeader);
                                    }

                                    isProcessed = true;
                                }
                            }

                            if (isProcessed)
                            {
                                break;
                            }
                        }
                    }

                    if (useCompression && !isEncodedContent &&
                        _compressionManager.IsSupportedMediaType(mediaType))
                    {
                        byte[] processedBytes = encoding.GetBytes(processedContent);

                        using (var inputStream = new MemoryStream(processedBytes))
                            using (var outputStream = new MemoryStream())
                            {
                                string      acceptEncoding = request.Headers["Accept-Encoding"];
                                ICompressor compressor     = _compressionManager.CreateCompressor(acceptEncoding);

                                using (Stream compressedStream = compressor.Compress(outputStream))
                                {
                                    await inputStream.CopyToAsync(compressedStream);
                                }

                                byte[] compressedBytes     = outputStream.ToArray();
                                int    compressedByteCount = compressedBytes.Length;

                                if (outputStream.CanWrite)
                                {
                                    outputStream.SetLength(0);
                                }
                                inputStream.SetLength(0);

                                responseHeaders["Content-Length"] = compressedByteCount.ToString();
                                compressor.AppendHttpHeaders(appendHttpHeader);
                                await originalStream.WriteAsync(compressedBytes, 0, compressedByteCount);
                            }

                        isProcessed = true;
                    }
                    else
                    {
                        if (isProcessed)
                        {
                            byte[] processedBytes     = encoding.GetBytes(processedContent);
                            int    processedByteCount = processedBytes.Length;

                            responseHeaders["Content-Length"] = processedByteCount.ToString();
                            await originalStream.WriteAsync(processedBytes, 0, processedByteCount);
                        }
                    }
                }

                if (!isProcessed)
                {
                    await originalStream.WriteAsync(cachedBytes, 0, cachedByteCount);
                }
            }
        }
        public async Task Invoke(HttpContext context)
        {
            bool useMinification = _options.IsMinificationEnabled() && _minificationManagers.Count > 0;
            bool useCompression  = _options.IsCompressionEnabled() && _compressionManager != null;

            if (!useMinification && !useCompression)
            {
                await _next.Invoke(context);

                return;
            }

            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            using (var cacheStream = new MemoryStream())
            {
                Stream originalStream = response.Body;
                response.Body = cacheStream;

                await _next.Invoke(context);

                byte[] cacheBytes  = cacheStream.ToArray();
                int    cacheSize   = cacheBytes.Length;
                bool   isProcessed = false;

                response.Body = originalStream;

                if (request.Method == "GET" && response.StatusCode == 200 &&
                    _options.IsAllowableResponseSize(cacheSize))
                {
                    string   contentType = response.ContentType;
                    string   mediaType   = null;
                    Encoding encoding    = Encoding.GetEncoding(0);

                    if (contentType != null)
                    {
                        MediaTypeHeaderValue mediaTypeHeader;

                        if (MediaTypeHeaderValue.TryParse(contentType, out mediaTypeHeader))
                        {
                            mediaType = mediaTypeHeader.MediaType.ToLowerInvariant();
                            encoding  = mediaTypeHeader.Encoding;
                        }
                    }

                    string      currentUrl  = request.Path.Value;
                    QueryString queryString = request.QueryString;
                    if (queryString.HasValue)
                    {
                        currentUrl += queryString.Value;
                    }

                    string content          = encoding.GetString(cacheBytes);
                    string processedContent = content;
                    Action <string, string> appendHttpHeader = (key, value) =>
                    {
                        response.Headers.Append(key, new StringValues(value));
                    };

                    if (useMinification)
                    {
                        foreach (IMarkupMinificationManager minificationManager in _minificationManagers)
                        {
                            if (mediaType != null && minificationManager.IsSupportedMediaType(mediaType) &&
                                minificationManager.IsProcessablePage(currentUrl))
                            {
                                IMarkupMinifier minifier = minificationManager.CreateMinifier();

                                MarkupMinificationResult minificationResult = minifier.Minify(processedContent, currentUrl, encoding, false);
                                if (minificationResult.Errors.Count == 0)
                                {
                                    processedContent = minificationResult.MinifiedContent;
                                    if (_options.IsPoweredByHttpHeadersEnabled())
                                    {
                                        minificationManager.AppendPoweredByHttpHeader(appendHttpHeader);
                                    }

                                    isProcessed = true;
                                }
                            }

                            if (isProcessed)
                            {
                                break;
                            }
                        }
                    }

                    if (useCompression && _compressionManager.IsSupportedMediaType(mediaType))
                    {
                        string acceptEncoding = request.Headers["Accept-Encoding"];

                        ICompressor compressor       = _compressionManager.CreateCompressor(acceptEncoding);
                        Stream      compressedStream = compressor.Compress(originalStream);
                        compressor.AppendHttpHeaders(appendHttpHeader);

                        using (var writer = new StreamWriter(compressedStream, encoding))
                        {
                            await writer.WriteAsync(processedContent);
                        }

                        isProcessed = true;
                    }
                    else
                    {
                        if (isProcessed)
                        {
                            using (var writer = new StreamWriter(originalStream, encoding))
                            {
                                await writer.WriteAsync(processedContent);
                            }
                        }
                    }
                }

                if (!isProcessed)
                {
                    cacheStream.Seek(0, SeekOrigin.Begin);
                    await cacheStream.CopyToAsync(originalStream);
                }

                cacheStream.SetLength(0);
            }
        }
Example #7
0
        private void Initialize()
        {
            if (_initialized.Set())
            {
                HttpRequest  request  = _context.Request;
                HttpResponse response = _context.Response;

                if (response.StatusCode == 200)
                {
                    string   httpMethod  = request.Method;
                    string   contentType = response.ContentType;
                    string   mediaType   = null;
                    Encoding encoding    = null;

                    if (contentType != null)
                    {
                        MediaTypeHeaderValue mediaTypeHeader;

                        if (MediaTypeHeaderValue.TryParse(contentType, out mediaTypeHeader))
                        {
                            mediaType = mediaTypeHeader.MediaType
#if ASPNETCORE2
                                        .Value
#endif
                                        .ToLowerInvariant()
                            ;
                            encoding = mediaTypeHeader.Encoding;
                        }
                    }

                    string      currentUrl  = request.Path.Value;
                    QueryString queryString = request.QueryString;
                    if (queryString.HasValue)
                    {
                        currentUrl += queryString.Value;
                    }

                    IHeaderDictionary responseHeaders = response.Headers;
                    bool isEncodedContent             = responseHeaders.IsEncodedContent();

                    if (_minificationManagers.Count > 0)
                    {
                        foreach (IMarkupMinificationManager minificationManager in _minificationManagers)
                        {
                            if (minificationManager.IsSupportedHttpMethod(httpMethod) &&
                                mediaType != null && minificationManager.IsSupportedMediaType(mediaType) &&
                                minificationManager.IsProcessablePage(currentUrl))
                            {
                                if (isEncodedContent)
                                {
                                    throw new InvalidOperationException(
                                              string.Format(
                                                  AspNetCommonStrings.MarkupMinificationIsNotApplicableToEncodedContent,
                                                  responseHeaders[HeaderNames.ContentEncoding]
                                                  )
                                              );
                                }

                                _currentMinificationManager = minificationManager;
                                _cachedStream        = new MemoryStream();
                                _minificationEnabled = true;

                                break;
                            }
                        }
                    }

                    if (_compressionManager != null && !isEncodedContent &&
                        _compressionManager.IsSupportedHttpMethod(httpMethod) &&
                        _compressionManager.IsSupportedMediaType(mediaType) &&
                        _compressionManager.IsProcessablePage(currentUrl))
                    {
                        string acceptEncoding = request.Headers[HeaderNames.AcceptEncoding];

                        ICompressor compressor = _compressionManager.CreateCompressor(acceptEncoding);
                        if (!(compressor is NullCompressor))
                        {
                            _currentCompressor  = compressor;
                            _compressionStream  = compressor.Compress(_originalStream);
                            _compressionEnabled = true;
                        }
                    }

                    _currentUrl = currentUrl;
                    _encoding   = encoding;
                }
            }
        }