jmcd
jmcd

Reputation: 4300

How can I intercept the HTML from a ViewResult, modify it and serve it up?

I'm writing a simple CMS.

I want to be able to load a View, having it included inside a master page, and then scan the HTML so that I can replace some custom tags (like {{blog}} with my own blog output) and then serve it up to the browser.

How can I get access to the HTML from the ViewResult in order to intercept it?

Upvotes: 3

Views: 2586

Answers (2)

Adrian Clark
Adrian Clark

Reputation: 12499

Sounds like you want to write an ActionFilterAttribute. This attribute has the following methods:

  • OnActionExecuting - called just before the decorated action is executed
  • OnActionExecuted - called after the action method is called, but before the ActionResult is rendered.
  • OnResultExecuting - callled before the result is rendered
  • OnResultExecuted - called after the result is rendered

There is an example here which returns either JSON or XML data depending on the "Content-type" header: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Upvotes: 4

Haacked
Haacked

Reputation: 59041

That's going to be tricky because the ViewResult writes its response directly to the Response.Stream. So you'll probably have to deal with the Response.Filter property to output the ViewResult to a MemoryStream so you can manipulate the content before returning a ContentResult. All this would happen in OnResultExecuting probably.

Upvotes: 4

Related Questions