asp.net filters illegal words using Response.Filter
- 2020-05-09 18:22:06
- OfStack
1 another solution is to filter out the very words, the output of the advantage is that you should just write one, can filter site of illegal words, disadvantage is that illegal words still deposited in the database, ha ha, you can choose a targeted, this example is the latter, the cause is that didn't do this, then you need to add, then don't want to change the original code, so I think this way, mainly adopted HttpResponse. Filter attributes to deal with. The specific code is as follows:
Start by customizing a class to act as a filter for illegal words
Then, in the Global.asax file, add the following code:
[code]
public void Application_BeginRequest(){
Response.Filter = new ResponseFilter(Response.Filter);
}
OK, test 1!
Start by customizing a class to act as a filter for illegal words
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);
// Get illegal word list, this can be in database or Web.Config Read out
string pattern = @"( Illegal words 1| Illegal words 2| Illegal words 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, in the Global.asax file, add the following code:
[code]
public void Application_BeginRequest(){
Response.Filter = new ResponseFilter(Response.Filter);
}
OK, test 1!