HttpHandler全站过滤替换Html输出

这几天,一直想找一个替换整站即将要输出到客户端Html方法,但是找了好多,都没有找到,找到最大级别的,也就是在页面中处理;再者,这两天又看到了dudu写的关于 outputcache bug 的文章,真让我感觉到,不理解原理看来真的不行的,没文化太可怕了,所以,必须要再次认真的审视下 HttpHandler 和 HttpModule 的作用及用法 啦
 
一些基本的概念,这里就不说了,本来自己的博客就是为自己做备忘的,如果不行本文被你看到,有疑问的话,可以直接给我留言 :-)
 
先说 HttpHandler ,其实自定义 HttpHandler 也是蛮简单的,但是这个的作用不是太大,自定义HttpHandler也主要用在静态文件的处理上面了,比如说 图片加水印、防盗链等等,都是对 静态文件做的处理,因为 HttpHandler 和 asp.net 中的Page 只能 2 选1 操作,所以,用来做处理动态页面,是不太便利的。(asp.net 中的Page,即 System.Web.UI.Page ,也是一个 HttpHandler,只不过是经过扩展的、复杂的 HttpHandler)。
 
再说下 HttpModule 吧 ,感觉 HttpModule 能处理的事情比较多,也相对比较重要,另外使用比之前者也简单很多,因为有 Global.asax 文件嘛,你懂得,不需要往 WebConfig 配置啦。
 
HttpModule 中的事件比较多,在各个事件中,做一些处理还是很不错的,对于一些较深入的应用,前提搞HttpModule 是必须的
 
页面直接上代码吧,这写代码主要是完成以下两个任务:
 
1. 全局过滤 站点的 HTML  输出
 
2. 页面加上 OutPutCache后 , HttpModule 中的事件是否还执行
 
App_Code/MyModule.cs:
 
using System;
using System.Web;
using System.IO;
using System.Text;

/// <summary>
///MyModule 的摘要说明
/// </summary>
namespace ModuleDemo
{

public class MyModule : IHttpModule
{
/*The Event
BeginRequest 指示请求处理开始
AuthenticateRequest 封装请求身份验证过程
AuthorizeRequest 封装检查是否能利用以前缓存的输出页面处理请求的过程
ResolveRequestCache 从缓存中得到相应时候触发
AcquireRequestState 加载初始化Session时候触发
PreRequestHandlerExecute 在Http请求进入HttpHandler之前触发
PostRequestHandlerExecute 在Http请求进入HttpHandler之后触发
ReleaseRequestState 存储Session状态时候触发
UpdateRequestCache 更新缓存信息时触发
EndRequest 在Http请求处理完成的时候触发
PreSendRequestHenaders 在向客户端发送Header之前触发
PreSendRequestConternt 在向客户端发送内容之前触发
*/

public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(BeginRequest);
app.AuthenticateRequest += new EventHandler(AuthenticateRequest);
app.AuthorizeRequest += new EventHandler(AuthorizeRequest);
app.ResolveRequestCache += new EventHandler(ResolveRequestCache);
app.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
app.PostRequestHandlerExecute += new EventHandler(PostRequestHandlerExecute);
app.ReleaseRequestState += new EventHandler(ReleaseRequestState);
app.UpdateRequestCache += new EventHandler(UpdateRequestCache);
app.EndRequest += new EventHandler(EndRequest);
app.PreSendRequestHeaders += new EventHandler(PreSendRequestHenaders);
app.PreSendRequestContent += new EventHandler(PreSendRequestConternt);
}

private void BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>BeginRequet!" + DateTime.Now.Millisecond.ToString() + "<br />");
app.Response.Filter = new ReplaceHtml(app.Response.Filter);
}

private void AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>AuthenticateRequest!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void AuthorizeRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>AuthorizeRequest!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void ResolveRequestCache(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>ResolveRequestCache!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void AcquireRequestState(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>AcquireRequestState!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>PreRequestHandlerExecute!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void PostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>PostRequestHandlerExecute!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void ReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>ReleaseRequestState!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void UpdateRequestCache(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>UpdateRequestCache!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void EndRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>EndRequest!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void PreSendRequestHenaders(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>PreSendRequestHenaders!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

private void PreSendRequestConternt(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("<span style='color:gray;'>Module : </span>PreSendRequestConternt!" + DateTime.Now.Millisecond.ToString() + "<br />");
}

public void Dispose() { }
}

public class ReplaceHtml : Stream
{
private Stream m_sink;
private long m_position;

public ReplaceHtml(Stream sink)
{
m_sink = sink;
}

public override int Read(byte[] buffer, int offset, int count)
{
return m_sink.Read(buffer, offset, count);
}

// Override the Write method to filter Response to a file.
public override void Write(byte[] buffer, int offset, int count)
{
string html = Encoding.UTF8.GetString(buffer);
html = html.Replace("Replace", "REPLACE");
byte[] b = Encoding.UTF8.GetBytes(html);
m_sink.Write(b, 0, b.Length);
}

// The following members of Stream must be overriden.
public override bool CanRead
{
get { return true; }
}

public override bool CanSeek
{
get { return false; }
}

public override bool CanWrite
{
get { return false; }
}

public override long Length
{
get { return 0; }
}

public override long Position
{
get { return m_position; }
set { m_position = value; }
}

public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return 0;
}

public override void SetLength(long length)
{
m_sink.SetLength(length);
}

public override void Close()
{
m_sink.Close();
}

public override void Flush()
{
m_sink.Flush();
}

}

}
 
default.aspx
 
<%@ Page Language="C#"%>
<%@ OutputCache VaryByParam="*" Duration="5"  %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Page Load At:o"+ DateTime.Now.Millisecond.ToString());
        label1.Text = "I'm a label!?";
    }

    protected override void Render(HtmlTextWriter writer)
    {
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
        base.Render(htmlWriter);
        string html = sw.ToString();
        //html = html.Replace("HTML","H TML");
        html = "<br />----Begin Render" + html + "----End Render<br />";
        writer.Write(html);
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  <title></title>
</head>
    <body style="font-family:微软雅?黑;margin:100px auto 100px 50px;"">
            <h1 style="color:gray;">页3面? HTML</h1>
            <h1 style="color:gray;">测a试? Replace</h1>
            <div><asp:Label runat="server" ID="label1"></asp:Label></div>
  </body>
</html>
  
 
Web.Config 配置:
 
 <httpModules>
            <add name="ModuleDemo" type="ModuleDemo.MyModule"/>
 </httpModules>


关键词: HttpHandler全站过滤Html输出,过滤页面Html代码,全站html过滤

原文地址:https://www.cnblogs.com/xunziji/p/2307603.html