简体   繁体   English

如何从ViewResult拦截HTML,修改它并提供它?

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

I'm writing a simple CMS. 我正在写一个简单的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. 我希望能够加载一个View,将其包含在母版页中,然后扫描HTML以便我可以用我自己的博客输出替换一些自定义标签(如{{blog}}),然后将其提供给浏览器。

How can I get access to the HTML from the ViewResult in order to intercept it? 如何从ViewResult访问HTML以拦截它?

That's going to be tricky because the ViewResult writes its response directly to the Response.Stream. 这将是棘手的,因为ViewResult将其响应直接写入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. 因此,您可能必须处理Response.Filter属性以将ViewResult输出到MemoryStream,以便您可以在返回ContentResult之前操作内容。 All this would happen in OnResultExecuting probably. 所有这些都可能发生在OnResultExecuting上。

Sounds like you want to write an ActionFilterAttribute . 听起来你想写一个ActionFilterAttribute This attribute has the following methods: 该属性具有以下方法:

  • OnActionExecuting - called just before the decorated action is executed OnActionExecuting - 在执行修饰操作之前调用
  • OnActionExecuted - called after the action method is called, but before the ActionResult is rendered. OnActionExecuted - 在调用action方法之后但在呈现ActionResult之前调用。
  • OnResultExecuting - callled before the result is rendered OnResultExecuting - 在呈现结果之前调用
  • OnResultExecuted - called after the result is rendered OnResultExecuted - 在渲染结果后调用

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 这里有一个示例,它返回JSON或XML数据,具体取决于“Content-type”标题: 使用ASP.NET MVC创建REST API,它同时使用Json和plain Xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取ViewResult的索引? - How can I get the Index of a ViewResult? 如何正确模拟我的controllercontext来测试ViewResult.ExecuteResult()? - How can I correctly mock my controllercontext to test ViewResult.ExecuteResult()? 如何将ASP.NET MVC ViewResult呈现为HTML? - How to render an ASP.NET MVC ViewResult to HTML? 如何拦截和修改批量更新? - How to intercept and modify bulk updates? ActionResult作为ViewResult返回null ..但我可以显式转换? - ActionResult as ViewResult returns null.. but I can explicitly cast? 如何在 DbContext 中拦截 ModelBuilder 实例? - How can I intercept the ModelBuilder instance in a DbContext? 自定义任务窗格:如何从插件中拦截 Excel 工作表的可见性变化? - Custom Task Pane: How can I intercept Excel worksheets' visibility change from the Addin? 如何修改以下代码以从数据库中提取数据? - How can I modify the following code to pull data from a database? 如何以及在何处修改DataAdapter中自动生成的查询? - How and where can I modify the auto generated query from DataAdapter? 如何从 xctk xceed 向导中的按钮修改样式? - How can I modify style from buttons in xctk xceed wizard?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM