代码改变世界

使用Response.Filter 过滤非法词汇

2010-03-02 11:09  杨延成  阅读(2440)  评论(3编辑  收藏  举报

一般信息发布网站,论坛等均具有实现非法词汇过滤功能,即当用户录入非法词汇时,进行替换,使其无法显示到页面上,针对此种功能,通常采用的时,在读取时,在读到非法词汇后,进行替换。另一种解决方案是在输出时过滤掉非常词汇,优点是只要写一次就好了,可以过滤整站的非法词汇,缺点是,非法词汇仍然存入到了数据库中,呵呵,大家可以有针对性的选择,本例用的是后者,起因在于当初没有做此功能,后来需要添加,这时又不想改原来代码,所以就想了这个办法,主要是采用了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,测试一下吧!