Question

I have a very basic ASP.NET response filter that works "fine." I use it to replace the domain for static resources.

My code in the controller looks like this:

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
            _cdnRewriter.Stream = filterContext.RequestContext.HttpContext.Response.Filter;
            filterContext.RequestContext.HttpContext.Response.Filter = _cdnRewriter;
    }

And the rewrite filter itself:

    public override void Write(byte[] buffer, int offset, int count)
    {
        var html = Encoding.Default.GetString(buffer, offset, count);

        //manipulate html

        byte[] outData = Encoding.Default.GetBytes(html);
        Stream.Write(outData, 0, outData.GetLength(0));
    }

For certain pages on my site (I can't find the rhyme or reason yet), I get a "HTTP Web Exception: Invalid use of response filter" perhaps 90% of the time. Simply refreshing a dozen times will get the correct output, but refreshing again will show the exception:

[HttpException (0x80004005): Invalid use of response filter]
   System.Web.HttpResponseStreamFilterSink.VerifyState() +4097234
   System.Web.HttpResponseStreamFilterSink.Write(Byte[] buffer, Int32 offset, Int32 count) +28
   NeoSmart.Web.CdnRewriteFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +452
   System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +359
   System.Web.HttpResponse.FilterOutput() +121
   System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +119
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

Am I doing something wrong in my response filter?

Was it helpful?

Solution

I probably should have known better: response filters should not be shared. I was using an object per class, creating a new response filter each time the OnActionExecuted function was called resolved the issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top