asp.net MVC 3/4相当于response.filter

编程入门 行业动态 更新时间:2024-10-20 05:32:42
本文介绍了asp MVC 3/4相当于response.filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在一个需要拦截所有将被发送到浏览器的HTML和替换一些标记,在那里。这将需要在全球范围内,并为每个视图完成。什么是3或4使用C#为此在ASP.net MVC的最佳方法是什么?在过去,我在ASP Web表单使用在Global.asax(VB)的response.filter做到了这一点。

I 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 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

这要求我创建了一个从的System.IO.Stream继承和通过HTML走到全部更换标签的类。我不知道对如何使用C#为此在ASP.NET MVC 4。正如你可能已经注意到我是一个完全newbee在MVC世界。

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.

推荐答案

您仍然可以使用响应过滤器在ASP.NET MVC:

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(); }

如果您要应用到所有的行动把它注册为在Global.asax中全球行动过滤器。

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

更多推荐

asp.net MVC 3/4相当于response.filter

本文发布于:2023-11-03 15:31:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555457.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:net   asp   MVC   filter   response

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!