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. 洛谷P3385负环

    传送门 #include <iostream> #include <cstdio> #include <cstring> #include <algorith ...

  2. ThinkPHP小知识点

    ThinkPHP模版中时间戳转换为时间 {$vo.data|date='Y-m-d',###} thinkphp字符截取函数msubstr() ThinkPHP有一个内置字符截取函数mb_substr ...

  3. 搜索入门之dfs--经典的迷宫问题解析

    今天来谈一下dfs的入门,以前看到的dfs入门,那真的是入门吗,都是把dfs的实现步骤往那一贴,看完是知道dfs的步骤了,但是对于代码实现还是没有概念.今天准备写点自己的心得,真的是字面意思--入门. ...

  4. GUC-7 同步锁 Lock

    import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * 一.用于解决 ...

  5. 自己封装的php Curl并发处理,欢迎提出问题优化。

    因为项目需要,发现一个一个发送请求实在太慢,无奈之下,我们可以封装一个并发处理的curl请求批处理句柄来减少重复创建句柄的问题 代码如下: /* *@param array $data url的参数 ...

  6. Singleton 多线程

    单例模式 何为单例模式,在GOF的<设计模式:可复用面向对象软件的基础>中是这样说的:保证一个类只有一个实例,并提供一个访问它的全局访问点.首先,需要保证一个类只有一个实例:在类中,要构造 ...

  7. spring boot在控制台输出彩色日志

    阅读org.springframework.boot.context.config.AnsiOutputApplicationListener 源码发现,通过向JVM传递参数,可以在控制台打印彩色日志 ...

  8. lr自带网站WebTours打不开

  9. mysql关于数据库表的水平拆分和垂直拆分

    最初知道水平垂直分表的时候是刚参加工作不久的时候,知道了这个概念,但是公司用户量和数据量始终没上来,所以也没用到过,知道有一天到了一家新公司后,这些才被应用到实际开发中,这里我就大概说说关于水平和垂直 ...

  10. vue 中 使用 tradingview

    加载页面时初始化方法: mounted 可以在 mounted 方法中调用 methods 的中的方法 使用 data 中的数据时,在每个方法的开始推荐先定义 var that = this 现在还不 ...