博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
asp.net MVC 3/4 equivalent to a response.filter
阅读量:6225 次
发布时间:2019-06-21

本文共 3785 字,大约阅读时间需要 12 分钟。

 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: .....
...

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.

///     /// Insert messages and script to display on client when a partial view is returned    ///     private class ResponseFilter : MemoryStream    {        private readonly Stream _response;        private readonly IList _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 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 detachMessages)        {            if (detachMessages.Count == 0)                return null;            var javascript = CustomJavaScriptSerializer.Instance.Serialize(detachMessages);            return "$(function(){var messages = " + javascript + @";// display messagesbase.ajaxHelper.displayMessages(messages);})";        }    }

 

转载地址:http://rhuna.baihongyu.com/

你可能感兴趣的文章
JobScheduler之超时检查
查看>>
最近找工作面试那些事儿(6月)
查看>>
简单VC内存检测
查看>>
Electron任务栏图标定制分析
查看>>
记一次简书图片403(hexo中简书图片迁移到阿里云oss)
查看>>
vue 2.0 路由切换以及组件缓存源代码重点难点分析
查看>>
清凉一夏,“极客时间”陪你过暑假
查看>>
掘金首秀
查看>>
vue面试整理
查看>>
React基础(一)
查看>>
PageRank 算法随记
查看>>
喜马拉雅 FM--- [ Java 高级开发] [ Java 架构师] [iOS 架构师] 招聘啦
查看>>
软能力那点事,你知多少
查看>>
前端小知识10点(2019.5.28)
查看>>
基于"发布-订阅"的原生JS插件封装
查看>>
深度掌握Redis:5大难题解决方案、单线程优劣势、高并发快原因等
查看>>
JavaScript系列之类型判断
查看>>
浮动 二 文字围绕现象(下)
查看>>
C#发送短信验证码
查看>>
vue-服务端渲染6:client/server-entry.js
查看>>