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
I think I've developed a pretty good way to do this.
OnClose
method and play with the stream as you like.public abstract class ReadOnlyActionFilterAttribute : ActionFilterAttribute
{
private delegate void ReadOnlyOnClose(Stream stream);
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Filter = new OnCloseFilter(
filterContext.HttpContext.Response.Filter,
this.OnClose);
base.OnActionExecuting(filterContext);
}
protected abstract void OnClose(Stream stream);
private class OnCloseFilter : MemoryStream
{
private readonly Stream stream;
private readonly ReadOnlyOnClose onClose;
public OnCloseFilter(Stream stream, ReadOnlyOnClose onClose)
{
this.stream = stream;
this.onClose = onClose;
}
public override void Close()
{
this.Position = 0;
this.onClose(this);
this.Position = 0;
this.CopyTo(this.stream);
base.Close();
}
}
}
You can then derive from this to another attribute to access the stream and get the HTML:
public class MyAttribute : ReadOnlyActionFilterAttribute
{
protected override void OnClose(Stream stream)
{
var html = new HtmlDocument();
html.Load(stream);
// play with html
}
}