我在一个需要拦截所有将被发送到浏览器的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
发布评论