一般信息發布網站,論壇等均具有實現非法詞匯過濾功能,即當用戶錄入非法詞匯時,進行替換,使 其無法顯示到頁面上,針對此種功能,通常采用的時,在讀取時,在讀到非法詞匯後,進行替換。另一種 解決方案是在輸出時過濾掉非常詞匯,優點是只要寫一次就好了,可以過濾整站的非法詞匯,缺點是,非 法詞匯仍然存入到了數據庫中,呵呵,大家可以有針對性的選擇,本例用的是後者,起因在於當初沒有做 此功能,後來需要添加,這時又不想改原來代碼,所以就想了這個辦法,主要是采用了 HttpResponse.Filter屬性來處理。具體代碼如下:
首先自定義一個類,來作為非法詞匯的過濾器
1 public class ResponseFilter:Stream
2 {
3 #region properties
4
5 Stream responseStream;
6 long position;
7 StringBuilder html = new StringBuilder();
8
9 #endregion
10
11 #region constructor
12
13 public ResponseFilter(Stream inputStream)
14 {
15
16 responseStream = inputStream;
17
18 }
19
20 #endregion
21
22 #region implemented abstract members
23
24 public override bool CanRead
25 {
26 get { return true; }
27 }
28
29 public override bool CanSeek
30 {
31 get { return true; }
32 }
33
34 public override bool CanWrite
35 {
36 get { return true; }
37 }
38
39 public override void Close()
40 {
41 responseStream.Close();
42 }
43
44 public override void Flush()
45 {
46 responseStream.Flush ();
47 }
48
49 public override long Length
50 {
51 get { return 0; }
52 }
53
54 public override long Position
55 {
56 get { return position; }
57 set { position = value; }
58 }
59
60 public override long Seek(long offset, System.IO.SeekOrigin direction)
61 {
62 return responseStream.Seek (offset, direction);
63 }
64
65 public override void SetLength(long length)
66 {
67 responseStream.SetLength(length);
68 }
69
70 public override int Read(byte[] buffer, int offset, int count)
71 {
72 return responseStream.Read(buffer, offset, count);
73 }
74
75 #endregion
76
77 #region write method
78
79 public override void Write(byte[] buffer, int offset, int count)
80 {
81
82 string sBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);
83
84 //得到非法詞匯列表,這個可以在數據庫或Web.Config中讀取出來
85 string pattern = @"(非法詞匯1|非法詞匯2|非法詞匯3)";
86
87
88 string[] s = pattern.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
89
90 foreach (string s1 in s)
91 {
92 sBuffer = sBuffer.Replace(s1, "**");
93 }
94
95
96 byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes (sBuffer);
97 responseStream.Write(data, 0, data.Length);
98
99 }
100
101 #endregion
102
103
104 }
然後再Global.asax文件中,添加如下代碼:
1 public void Application_BeginRequest()
2 {
3 Response.Filter = new ResponseFilter(Response.Filter);
4
5 }
OK,測試一下吧!