Search code examples
asp.net-mvcflushaction-filteractionfilterattribute

Flushing and Compression filters (ASP.NET MVC)


We have quite common code which worked fine:

public class CompressionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.HttpContext.Request;
        if (request.IsAjaxRequest())
            return;

        string acceptEncoding = request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(acceptEncoding)) return;
        acceptEncoding = acceptEncoding.ToUpperInvariant();
        HttpResponseBase response = filterContext.HttpContext.Response;

        if (acceptEncoding.Contains("GZIP"))
        {
             response.AppendHeader("Content-encoding", "gzip");
             response.Filter = new WhitespaceFilter(new GZipStream(response.Filter, CompressionMode.Compress));
        }
        else if (acceptEncoding.Contains("DEFLATE"))
        {
             response.AppendHeader("Content-encoding", "deflate");
             response.Filter =  new WhitespaceFilter(new DeflateStream(response.Filter, CompressionMode.Compress));
        }
    }
}

Now I am trying to use Response.Flush() to deliver part of the page, to improve user experience. With this scenario, when response.Filter is modified by each write operation it is clear that the page needs to be delivered at once. How I can make my application to write to an intermediate stream, then compress it, and then push to Response.Filter?


Solution

  • So far, this seems to be not solvable, because asp.net use same stream for input and output for filters