Another solution is to filter out frequently used words during output. The advantage is that you only need to write them once and can filter out the illegal words on the entire site. The disadvantage is that the illegal words are still stored in the database, haha, you can make a specific choice. This example uses the latter because you didn't have this function and need to add it later. At this time, you don't want to change the original code, so I thought about this method, mainly using HttpResponse. filter attribute. The Code is as follows:
First, define a class as a filter for illegal words.
Copy codeThe Code is as follows:
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 );
// Obtain the list of invalid words, which can be read from the database or Web. Config.
String pattern = @ "(Illegal word 1 | illegal word 2 | illegal word 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
}
Then add the following code to the Global. asax file:
[Code]
Public void Application_BeginRequest (){
Response. Filter = new ResponseFilter (Response. Filter );
}
OK. Test it!