asp.net 使用Response.Filter 過濾非法詞彙

來源:互聯網
上載者:User

另一種解決方案是在輸出時過濾掉非常詞彙,優點是只要寫一次就好了,可以過濾整站的非法詞彙,缺點是,非法詞彙仍然存入到了資料庫中,呵呵,大家可以有針對性的選擇,本例用的是後者,起因在於當初沒有做此功能,後來需要添加,這時又不想改原來代碼,所以就想了這個辦法,主要是採用了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,測試一下吧!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.