Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

asp.net MVC 3/4 equivalent to a 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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...