Capturing HTML output with a controller action filter

前端 未结 4 1970
温柔的废话
温柔的废话 2020-12-14 13:17

I\'ve got the following filter in place on an action to capture the HTML output, convert it to a string, do some operations to modify the string, and return a ContentResult

4条回答
  •  既然无缘
    2020-12-14 13:48

    I solved this by hijacking the HttpWriter, and having it write into a StringBuilder rather than the response, and then doing whatever needs to be done to/with the response before writing it to the output.

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

提交回复
热议问题