1、Global.asax 文件中写一下代码
void Application_BeginRequest(object sender, EventArgs e) { // 在应用程序关闭时运行的代码 if (Request != null && Request.Headers != null) { if (Request.Headers.AllKeys.Contains("Accept")) { if (!string.IsNullOrEmpty(Request.Headers["Accept"])) { if (Request.Headers["Accept"].ToLower().Contains("text/html")) { Response.Filter=new ResponseFilter(Response.Filter); } } } } }
2、新增过滤器类 ResponseFilter.cs 代码如下
using DotNet.Utilities; using Lucene.Net.Util.Cache; using System; using System.Activities.Expressions; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; /// <summary> /// ResponseFilter 的摘要说明 /// </summary> public class ResponseFilter : Stream { #region properties Stream responseStream; long position; StringBuilder html = new StringBuilder(); #endregion #region constructor public ResponseFilter(Stream inputStream) { responseStream = inputStream; } #endregion #region implemented abstract members public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Close() { responseStream.Close(); } public override void Flush() { responseStream.Flush(); } public override long Length { get { return 0; } } public override long Position { get { return position; } set { position = value; } } public override long Seek(long offset, System.IO.SeekOrigin direction) { return responseStream.Seek(offset, direction); } public override void SetLength(long length) { responseStream.SetLength(length); } public override int Read(byte[] buffer, int offset, int count) { return responseStream.Read(buffer, offset, count); } #endregion #region write method public override void Write(byte[] buffer, int offset, int count) { string sBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count); var pattern = new List<string>();//敏感词列表 // //从配置文件 或任意其它地方 初始化 敏感词列表 // foreach (string s1 in pattern) { if (!string.IsNullOrEmpty(s1)) { if (s1.Contains("^")) { var _ss = s1.Split(new[] { '^' }, StringSplitOptions.None); sBuffer = sBuffer.Replace(_ss[0], _ss[1]); } else { sBuffer = sBuffer.Replace(s1, "***"); } } } byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(sBuffer); responseStream.Write(data, 0, data.Length); } #endregion }