c# – 使用控制器动作过滤器捕获HTML输出

前端之家收集整理的这篇文章主要介绍了c# – 使用控制器动作过滤器捕获HTML输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在捕获 HTML输出的动作上有以下过滤器,将其转换为字符串,执行一些操作以修改字符串,并返回带有新字符串的ContentResult.不幸的是,我一直以一个空字符串结束.
private class UpdateFilter : ActionFilterAttribute
    {
        private Stream stream;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stream = filterContext.HttpContext.Response.Filter;
            stream = new MemoryStream();
            filterContext.HttpContext.Response.Filter = stream;
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            StreamReader responsereader = new StreamReader(filterContext.HttpContext.Response.Filter);  //empty stream? why?
            responsereader.BaseStream.Position = 0;
            string response = responsereader.ReadToEnd();
            ContentResult contres = new ContentResult();
            contres.Content = response;
            filterContext.Result = contres;
        }
    }

我已经确定了StreamReader(stream).ReadToEnd()返回一个空字符串,但我无法弄清楚原因.@H_404_5@

任何想法如何解决这一问题?@H_404_5@

编辑:我已经将OnActionExecuted更改为OnResultExecuted,现在在生成View之后调用它,但是流仍然是空的!@H_404_5@

解决方法

我通过劫持HttpWriter解决了这个问题,并将其写入StringBuilder而不是响应,然后在将其写入输出之前执行需要对响应执行的任何操作.
private class UpdateFilter : ActionFilterAttribute
    {
        private HtmlTextWriter tw;
        private StringWriter sw;
        private StringBuilder sb;
        private HttpWriter output;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            sb = new StringBuilder();
            sw = new StringWriter(sb);
            tw = new HtmlTextWriter(sw);
            output = (HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;
            filterContext.RequestContext.HttpContext.Response.Output = tw;
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            string response = sb.ToString();
            //response processing
            output.Write(response);
        }
    }

猜你在找的C#相关文章