欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net 使用Response.Filter 过滤非法词汇

程序员文章站 2024-03-08 09:48:46
另一种解决方案是在输出时过滤掉非常词汇,优点是只要写一次就好了,可以过滤整站的非法词汇,缺点是,非法词汇仍然存入到了数据库中,呵呵,大家可以有针对性的选择,本例用的是后者,...
另一种解决方案是在输出时过滤掉非常词汇,优点是只要写一次就好了,可以过滤整站的非法词汇,缺点是,非法词汇仍然存入到了数据库中,呵呵,大家可以有针对性的选择,本例用的是后者,起因在于当初没有做此功能,后来需要添加,这时又不想改原来代码,所以就想了这个办法,主要是采用了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,测试一下吧!