am in a need to intercept all of the html that will be sent to the browser and replace some tags that are there. this will need to be done globally and for every view. what is the best way to do this in ASP.NET MVC 3 or 4 using C#? In past I have done this in ASP.net Webforms using the 'response.filter' in the Global.asax (vb)

Private Sub Global_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRequestHandlerExecute
Response.Filter = New ReplaceTags(Response.Filter)
End Sub

this calls a class I created that inherits from the system.io.stream and that walked through the html to replace all the tags. I have no idea as to how to do this in ASP.NET MVC 4 using C#. As you might have noticed I am a completely newbee in the MVC world.

You could still use a response filter in ASP.NET MVC:

public class ReplaceTagsFilter : MemoryStream
{
private readonly Stream _response;
public ReplaceTagsFilter(Stream response)
{
_response = response;
} public override void Write(byte[] buffer, int offset, int count)
{
var html = Encoding.UTF8.GetString(buffer);
html = ReplaceTags(html);
buffer = Encoding.UTF8.GetBytes(html);
_response.Write(buffer, offset, buffer.Length);
} private string ReplaceTags(string html)
{
// TODO: go ahead and implement the filtering logic
throw new NotImplementedException();
}
}

and then write a custom action filter which will register the response filter:

public class ReplaceTagsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;
response.Filter = new ReplaceTagsFilter(response.Filter);
}
}

and now all that's left is decorate the controllers/actions that you want to be applied this filter:

[ReplaceTags]
public ActionResult Index()
{
return View();
}

or register it as a global action filter in Global.asax if you want to apply to all actions.

The answer is correct but. After using it for a while I came across a case when the response is split in many parts so that html is incorrect

Part 1:
<html>.....<labe Part 2:
l/>...</html>

Also partial renders may make unexpected cases. Their html is out of the main stream too. So my solution is to do it in the Flush method after all streaming is done.

    /// <summary>
/// Insert messages and script to display on client when a partial view is returned
/// </summary>
private class ResponseFilter : MemoryStream
{
private readonly Stream _response;
private readonly IList<object> _detachMessages; public override void Flush()
{ // add messages and remove
// filter is called for a number of methods on one page (BeginForm, RenderPartial...)
// so that we don't need to add it more than once var html = MessageAndScript(_detachMessages);
var buffer = Encoding.UTF8.GetBytes(html);
_detachMessages.Clear();
_response.Write(buffer, 0, buffer.Length); base.Flush();
} public ResponseFilter(Stream response, IList<object> detachMessages)
{
_response = response;
_detachMessages = detachMessages;
} public override void Write(byte[] buffer, int offset, int count)
{
_response.Write(buffer, offset, buffer.Length);
} private static string MessageAndScript(IList<object> detachMessages)
{ if (detachMessages.Count == 0)
return null; var javascript = CustomJavaScriptSerializer.Instance.Serialize(detachMessages); return "$(function(){var messages = " + javascript + @";
// display messages
base.ajaxHelper.displayMessages(messages);
})";
}
}

asp.net MVC 3/4 equivalent to a response.filter的更多相关文章

  1. 在ASP.NET MVC中的四大筛选器(Filter)及验证实现

    http://www.cnblogs.com/artech/archive/2012/08/06/action-filter.html http://www.cnblogs.com/ghhlyy/ar ...

  2. ASP.NET MVC学习(三)之过滤器Filter

    http://www.cnblogs.com/yaopengfei/p/7910763.html

  3. ASP.NET MVC Filters 4种默认过滤器的使用【附示例】

    过滤器(Filters)的出现使得我们可以在ASP.NET MVC程序里更好的控制浏览器请求过来的URL,不是每个请求都会响应内容,只响应特定内容给那些有特定权限的用户,过滤器理论上有以下功能: 判断 ...

  4. ASP.Net请求处理机制初步探索之旅 - Part 5 ASP.Net MVC请求处理流程

    好听的歌 我一直觉得看一篇文章再听一首好听的歌,真是种享受.于是,我在这里嵌入一首好听的歌,当然你觉得不想听的话可以点击停止,歌曲 from 王菲 <梦中人>: --> 开篇:上一篇 ...

  5. 16、ASP.NET MVC入门到精通——MVC过滤器

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 在ASP.NET MVC中有四种过滤器类型

  6. 一种仿照Asp.net Mvc思维构建WebSocket服务器的方法

    问题场景 Asp.net Mvc提供了DependencyResolver.Routing.Filter. Modelbinder等webForm所没有新概念,提高Web服务编写的便利性,记得很久之前 ...

  7. ASP.NET MVC的Action Filter

    一年前写了一篇短文ASP.NET MVC Action Filters,整理了Action Filter方面的资源,本篇文章详细的描述Action Filter.Action Filter作为一个可以 ...

  8. Asp.net Mvc WebSocket

    转载一种仿照Asp.net Mvc思维构建WebSocket服务器的方法 问题场景 Asp.net Mvc提供了DependencyResolver.Routing.Filter. Modelbind ...

  9. ASP.Net MVC请求处理流程

    ASP.Net MVC请求处理流程 好听的歌 我一直觉得看一篇文章再听一首好听的歌,真是种享受.于是,我在这里嵌入一首好听的歌,当然你觉得不想听的话可以点击停止,歌曲 from 王菲 <梦中人& ...

随机推荐

  1. type Iterator does not take parameters

    在ubuntu编译java程序时报错:type Iterator does not take parameters 源码如下: package object; import java.util.*; ...

  2. Sourcetree使用 - git图形化工具(三)

    前面两个章节总结了Sourcetree的安装与配置Sourcetree密钥,这个章节主要讲如何使用Sourcetree.以前呢,都是使用git Bash进行命令行方式进行操作git,感觉部分时间浪费在 ...

  3. 【58沈剑架构系列】微服务架构之RPC-client序列化细节

    第一章聊了[“为什么要进行服务化,服务化究竟解决什么问题”] 第二章聊了[“微服务的服务粒度选型”] 上一篇聊了[“为什么说要搞定微服务架构,先搞定RPC框架?”] 通过上篇文章的介绍,知道了要实施微 ...

  4. python开发学习-day14(jquery、ajax等)

    s12-20160421-day14 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...

  5. LoadRunner FAQ

    LoadRunner FAQ web_concurrent_start和web_concurrent_end web_concurrent_start 语法: int web_concurrent_s ...

  6. Vue中directives的用法

    关于 vue 中 directives 的用法问题,详细可以参考vue官方对directives的解释 当前文章主要讲述directives怎么用,directives做权限按钮的功能 ###1. d ...

  7. Ionic入门二:网格(Grid)页面布局

    ionic 的网格(Grid)和其他大部分框架有所不同,它采用了弹性盒子模型(Flexible Box Model) .而且在移动端,基本上的手机都支持.row 样式指定行,col 样式指定列. 1. ...

  8. CSUOJ 1011 Counting Pixels

    Description Did you know that if you draw a circle that fills the screen on your 1080p high definiti ...

  9. 《Playing hard exploration games by watching YouTube》论文解读

    论文链接 油管链接 一.摘要   当环境奖励特别稀疏的时候,强化学习方法通常很难训练(traditionally struggle).一个有效的方式是通过人类示范者(human demonstrato ...

  10. 论 ArrayList如何实现线程安全

    一:使用synchronized关键字 二:使用Collections.synchronizedList(); 假如你创建的代码如下:List<Map<String,Object>& ...