包装/修改Html结果

Kas*_*dum 2 c# asp.net-mvc

基本上我们处在一个主要的hacky情况.我们有一些链接到其他网站的网页.但是,要求是此站点与链接到我们的站点具有相同的布局.这最初是通过请求原始页面,抓取布局以及在其布局中包装内容来完成的.

这在Web窗体中相当简单,因为我们可以简单地创建一个子类化的页面,它会覆盖Render方法,然后将我们在外部站点布局中生成的任何内容包装起来.但是,现在这个项目正在ASP.NET MVC中重写.

我们如何才能了解MVC操作创建的HTML结果,根据需要修改它们并将修改后的结果输出到浏览器?

tug*_*erk 9

您可以使用ActionFilterAttribute.OnResultExecuted方法

您可以在此处查看ActionFilters上的更多示例:

http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

编辑

关于这个主题有一篇很棒的博客文章:

http://weblogs.asp.net/imranbaloch/archive/2010/09/26/moving-asp-net-mvc-client-side-scripts-to-bottom.aspx

总结一下,你需要调整你的输出.据我所知,你需要使用RegEx来获取调整完整HTML所需的部分,你可以这样做:

这是一个助手类:

public class HelperClass : Stream {

    //Other Members are not included for brevity

    private System.IO.Stream Base;

    public HelperClass(System.IO.Stream ResponseStream)
    {
        if (ResponseStream == null)
            throw new ArgumentNullException("ResponseStream");
        this.Base = ResponseStream;
    }

    StringBuilder s = new StringBuilder();

    public override void Write(byte[] buffer, int offset, int count) {

        string HTML = Encoding.UTF8.GetString(buffer, offset, count);

        //In here you need to get the portion out of the full HTML
        //You can do that with RegEx as it is explain on the blog pots link I have given
        HTML += "<div style=\"color:red;\">Comes from OnResultExecuted method</div>";

        buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
        this.Base.Write(buffer, 0, buffer.Length);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是你的过滤器:

public class MyCustomAttribute : ActionFilterAttribute {

    public override void OnActionExecuted(ActionExecutedContext filterContext) {

        var response = filterContext.HttpContext.Response;

        if (response.ContentType == "text/html") {
            response.Filter = new HelperClass(response.Filter);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要在Global.asax文件Application_Start方法中注册此方法,如下所示:

protected void Application_Start() {

    //there are probably other codes here but I cut them out to stick with point here

    GlobalFilters.Filters.Add(new MyCustomAttribute());
}
Run Code Online (Sandbox Code Playgroud)