基本上我们处在一个主要的hacky情况.我们有一些链接到其他网站的网页.但是,要求是此站点与链接到我们的站点具有相同的布局.这最初是通过请求原始页面,抓取布局以及在其布局中包装内容来完成的.
这在Web窗体中相当简单,因为我们可以简单地创建一个子类化的页面,它会覆盖Render方法,然后将我们在外部站点布局中生成的任何内容包装起来.但是,现在这个项目正在ASP.NET MVC中重写.
我们如何才能了解MVC操作创建的HTML结果,根据需要修改它们并将修改后的结果输出到浏览器?
您可以使用ActionFilterAttribute.OnResultExecuted方法
您可以在此处查看ActionFilters上的更多示例:
编辑
关于这个主题有一篇很棒的博客文章:
总结一下,你需要调整你的输出.据我所知,你需要使用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)