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. JAVA复习笔记:内存结构和类加载

    Part1:JVM内存结构 JVM定义了若干个程序执行期间使用的数据区域.这个区域里的一些数据在JVM启动的时候创建,在JVM退出的时候销毁.而其他的数据依赖于每一个线程,在线程创建时创建,在线程退出 ...

  2. Hive与HBase区别 大墨垂杨

    大墨垂杨 http://www.cnblogs.com/quchunhui/p/5340989.html

  3. Python中super的应用

    约定 单继承 多继承 super 是个类 多继承中 super 的工作方式 参考资料 约定 在开始之前我们来约定一下本文所使用的 Python 版本.默认用的是 Python 3,也就是说:本文所定义 ...

  4. centos killall安装

    https://blog.csdn.net/joeyon1985/article/details/46707865 https://blog.csdn.net/xupeng874395012/arti ...

  5. Web前端开发最佳实践(10):JavaScript代码不好读,不好维护?你需要改变写代码的习惯

    前言 这篇文章本应该在上一篇文章:使用更严格的JavaScript编码方式,提高代码质量之前发布,但当时觉得这篇文章太过基础,也就作罢.后来咨询了一些初级的开发者,他们觉得有必要把这篇文章也放上来.尽 ...

  6. 包装印刷行业裕同集团&易普优APS项目顺利验收!

    裕同集团&易普优APS项目于2017年7月启动,2018年1月上线,2018年5月初项目顺利验收!历时十个月,龙岗作为裕同集团APS的先锋试点项目,同时也是业务最复杂的分公司,双方联合团队紧密 ...

  7. R语言编程艺术(1)快速入门

    这本书与手上其他的R语言参考书不同,主要从编程角度阐释R语言,而不是从统计角度.因为之前并没有深刻考虑这些,因此写出的代码往往是一条条命令的集合,并不像是“程序”,因此,希望通过学习这本书,能提高编程 ...

  8. git 设置bitbucket 邮箱、用户

    1. git config --global user.name "youname" 2 .git config --global user.email "youeami ...

  9. My blog in AI ---神经网络,网络架构

    上一篇博文中,我们介绍了神经网络中的神经元,那么该如何组织起来这些神经元,才能发挥出最好的效果去解决现实中的问题呢? 这是一个复杂的问题,在工程中,神经网络的架构也是训练的也是一种超参数,本节先在理论 ...

  10. Java工具类- 跨域工具类

    原本Spring MVC项目添加跨域: 在web.xml文件中配置: <!-- cors解决跨域访问问题 --> <filter> <filter-name>cor ...