I have a need to capture all the rendered output/html of a view so that I can persist the result. How can I do this within ASP.NET MVC?
-
I think you need to write an httpmodule, but I'm not quite sure...eKek0– eKek02009-05-07 15:04:36 +00:00Commented May 7, 2009 at 15:04
-
Just to clarify, I'm aware of that solution. I'm just curious to see if there's another place to hook into the mvc stack to capture the info.jbenckert– jbenckert2009-05-07 15:07:34 +00:00Commented May 7, 2009 at 15:07
2 Answers
There's a great post about partial output caching and includes code about how to capture output using an attribute.
The post: http://blog.codeville.net/2008/10/15/partial-output-caching-in-aspnet-mvc/
The code: http://blog.codeville.net/blogfiles/2008/October/ActionOutputCacheAttribute.cs
Comments
MVC Views output to the response stream via an HtmlTextWriter object in the HttpContext. So, one way to accomplish your task is to replace the existing HttpContext object with a new which contains an HtmlTextWriter that is outputting to a StringBuilder rather than the response stream.
This is reasonably straightforward if a little complicated and is covered in some detail in this blog post: http://andrewlocatelliwoodcock.com/2011/04/28/capturing-the-output-of-a-view-as-a-string/
I have used this technique successfully to capture View output as it is sent to the browser.
Don't forget: if you want to actually see the View as well, once you have captured the output you will also need to write it to the response stream ...