3

我有一个非常基本的 ASP.NET 响应过滤器,它工作“很好”。我用它来替换静态资源的域。

我在控制器中的代码如下所示:

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

而重写过滤器本身:

    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));
    }

对于我网站上的某些页面(我还找不到押韵或原因),我可能在 90% 的情况下收到“HTTP Web 异常:响应过滤器的无效使用”。简单地刷新十几次就会得到正确的输出,但是再次刷新会出现异常:

[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

我在响应过滤器中做错了吗?

4

1 回答 1

0

我可能应该更清楚:不应共享响应过滤器。我在每个类中使用一个对象,每次OnActionExecuted调用该函数时都会创建一个新的响应过滤器来解决问题。

于 2012-11-14T20:48:36.550 回答