富贵资源网 Design By www.hznty.com
另一种解决方案是在输出时过滤掉非常词汇,优点是只要写一次就好了,可以过滤整站的非法词汇,缺点是,非法词汇仍然存入到了数据库中,呵呵,大家可以有针对性的选择,本例用的是后者,起因在于当初没有做此功能,后来需要添加,这时又不想改原来代码,所以就想了这个办法,主要是采用了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,测试一下吧!
富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com