当前位置: 首页 > 编程语言 > C#

使用控制器操作过滤器捕获HTML输出

时间:2023-04-11 01:55:25 C#

使用控制器操作过滤器捕获HTML输出返回带有新字符串的ContentResult。不幸的是,我一直以空字符串结尾。私有类UpdateFilter:ActionFilterAttribute{私有流流;publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext){stream=filterContext.HttpContext.Response.Filter;流=新的内存流();filterContext.HttpContext.Response.Filter=stream;}publicoverridevoidOnResultExecuted(ResultExecutedContextfilterContext){StreamReaderresponsereader=newStreamReader(filterContext.HttpContext.Response.Filter);//空流?为什么?responsereader.BaseStream.Position=0;字符串响应=responsereader.ReadToEnd();ContentResultnewContent=contentResult();contres.Content=响应;filterContext.Result=contres;我已经确定StreamReader(stream).ReadToEnd()返回一个空字符串,但我不知道为什么。任何想法如何解决这一问题?编辑:我已将OnActionExecuted更改为OnResultExecuted,现在在生成视图后调用它,但流仍然是空的!我通过劫持HttpWriter并将其写入StringBuilder而不是响应来解决此问题,然后在将其写入输出之前对响应执行任何需要完成的操作。私有类UpdateFilter:ActionFilterAttribute{privateHtmlTextWritertw;私人StringWriter软件;私人StringBuilder某人;私有HttpWriter输出;publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext){sb=newStringBuilder();sw=新的StringWriter(sb);tw=新的HtmlTextWriter(sw);output=(HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;filterContext.RequestContext.HttpContext.Response.Output=tw;}publicoverridevoidOnResultExecuted(ResultExecutedContextfilterContext){stringresponse();//响应处理output.Write(response);}}尝试通过设置Position=0将流倒回到开头;位置=0;在你阅读它之前。publicoverridevoidOnActionExecuted(ActionExecutedContextfilterContext){stream.Position=0;字符串响应=newStreamReader(stream).ReadToEnd();ContentResultcontres=newContentResult();contres.Content=响应;filterContext.Result=contres;我想我已经开发出一种非常好的方法来做到这一点。公共抽象类ReadOnlyActionFilterAttribute:ActionFilterAttribute{privatedelegatevoidReadOnlyOnClose(Streamstream);publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext){filterContext.HttpContext.Response.Filter=newOnCloseFilter(filterContext.HttpContext.Response.Filter,this.OnClose);base.OnActionExecuting(filterContext);}protectedabstractvoidOnClose(Streamstream);私有类OnCloseFilter:MemoryStream{私有只读流流;私人只读ReadOnlyOnCloseonClose;publicOnCloseFilter(Streamstream,ReadOnlyOnCloseonClose){this.stream=stream;this.onClose=onClose;}publicoverridevoidClose(){this.Position=0;这个.onClose(这个);这个.位置=0;这个.CopyTo(this.stream);基地.关闭();}}}然后,您可以从这个派生到另一个属性以访问流并获取HTML:publicclassMyAttribute:ReadOnlyActionFilterAttribute{HTml.Load(流);//玩html}}你能验证OnActionExectuted方法中的流不为NULL吗?我不确定stream变量的状态是通过进程存储的..为什么不尝试从filterContext中获取stream:以上是C#学习教程:使用controlleractionfilter捕获整个内容HTML输出分享,如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——字符串响应=newStreamReader(stream).ReadToEnd();ContentResultcontres=newContentResult();contres.Content=响应;filterContext.Result=contres;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: