当重写ASP.NET输出时出现“响应过滤器的无效使用”错误

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 Exception: Invalid use of response filter”的错误。只需刷新几次即可得到正确输出,但再次刷新会显示异常情况。
[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

在我的响应过滤器中,我做错了什么吗?

1个回答

0

我可能应该知道得更清楚:响应过滤器不应该共享。我为每个类使用一个对象,每次调用OnActionExecuted函数时创建一个新的响应过滤器解决了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接