另一種解決方案是在輸出時過濾掉非常詞匯,優點是只要寫一次就好了,可以過濾整站的非法詞匯,缺點是,非法詞匯仍然存入到了數據庫中,呵呵,大家可以有針對性的選擇,本例用的是後者,起因在於當初沒有做此功能,後來需要添加,這時又不想改原來代碼,所以就想了這個辦法,主要是采用了HttpResponse.Filter屬性來處理。具體代碼如下:
首先自定義一個類,來作為非法詞匯的過濾器
復制代碼 代碼如下:
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);
//得到非法詞匯列表,這個可以在數據庫或Web.Config中讀取出來
string pattern = @"(非法詞匯1|非法詞匯2|非法詞匯3)";
string[] s = pattern.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s1 in s)
{
sBuffer = sBuffer.Replace(s1, "**");
}
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(sBuffer);
responseStream.Write(data, 0, data.Length);
}
#endregion
}
然後再Global.asax文件中,添加如下代碼:
[code]
public void Application_BeginRequest(){
Response.Filter = new ResponseFilter(Response.Filter);
}
OK,測試一下吧!