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. json字符串与java对象的相互转换(jackson)

    1.java对象转换为json字符串 package com.chichung.json; import com.fasterxml.jackson.core.JsonProcessingExcept ...

  2. MySQL 5.1完全卸载

    第一步:控制面板里的增加删除程序内进行删除 第二步:删除MySQL文件夹下的my.ini文件,如果备份好,可以直接将文件夹全部删除 第三步:regedit进入注册表 HKEY_LOCAL_MACHIN ...

  3. Centos之字符串搜索命令grep

    grep [选项] 字符串 文件名 在文件当中匹配符合条件的字符串 选项: -i 忽略大小写 -v 排除指定字符串 [root@localhost ~]# grep "work" ...

  4. javascript数组元素的添加、删除与插入以及参数数组的使用

    1.数组元素的添加 push方法在数组的尾部添加元素: var colorArray=new Array(); colorArray.push('red','black','yellow'); //这 ...

  5. 使用CSS3 @media 设置页面自适应

    参考CSS3 @media 查询 如果文档宽度小于 300 像素则修改背景演示(background-color): @media screen and (max-width: 300px) { bo ...

  6. LoadRunner脚本篇

    LoadRunner脚本篇     1概述 2脚本录制 3脚本编写 4脚本调试   关  键  词:LoadRunner 性能测试脚本 摘      要:编写一个准确无误的脚本对性能测试有至关重要的意 ...

  7. 黑马程序员_java基础笔记(05)...String类

    —————————— ASP.Net+Android+IOS开发..Net培训.期待与您交流!—————————— java.lang包 基本信息中 String就是C++.java等编程语言中的字符 ...

  8. 使用 AVA 做自动化测试

    http://colabug.com/710736.html

  9. 20169211《Linux内核原理与分析》 第十周作业

    一.Linux内核之进程地址空间学习总结 Linux内核除了要管理物理内存还需要管理虚拟内存.用户进程的地址空间就是虚拟内存的一部分.每个用户进程都独有一个地址空间.由于是虚拟化的内存,所以从每个进程 ...

  10. 在Ubuntu18.04中QT编程的环境构建(转)

    在Ubuntu18.04中QT编程的环境构建 原点分析 百家号06-2110:14 如果说QT大家觉得陌生的话,那么 Windows 早年推出的C++图形用户界面的应用程序开发框架MFC,应该是耳熟能 ...