asp.net MVC 3/4相当于response.filter [英] asp.net MVC 3/4 equivalent to a response.filter

查看:169
本文介绍了asp.net MVC 3/4相当于response.filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个需要拦截所有将被发送到浏览器的HTML和替换一些标记,在那里。这将需要在全球范围内,并为每个视图完成。什么是3或4使用C#为此在ASP.NET MVC的最佳方法是什么?在过去,我在ASP.net 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.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

这要求我创建了一个从的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆