与控制器动作过滤器捕获的HTML输出 [英] Capturing HTML output with a controller action filter
问题描述
我得上的操作到位以下筛选捕捉到HTML输出,其转换为字符串,做一些操作,以修改字符串,并用新的字符串返回ContentResult类型,不幸的是,我一直在结束了一个空字符串。
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 with the new string. Unfortunately, I keep ending up with an empty string.
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(流).ReadToEnd()返回一个空字符串,但我想不出为什么。
I've pinned down that StreamReader(stream).ReadToEnd() returns an empty string, but I can't figure out why.
任何想法如何解决这一问题?
Any ideas how to fix this?
修改:我已经改变了OnActionExecuted到OnResultExecuted,现在已经产生了查看后的叫法,但流仍然是空的。
EDIT: I've changed the OnActionExecuted to OnResultExecuted, and now it is called after the View has been generated, but the stream is still empty!
推荐答案
我解决了这个被劫持HttpWriter,并有记录到一个的StringBuilder
而非响应,然后做任何需要它写入输出前需做/与响应。
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);
}
}
这篇关于与控制器动作过滤器捕获的HTML输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!