一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net c非法词汇的过滤器

时间:2022-06-25 05:05:29 编辑:袖梨 来源:一聚教程网

asp教程.net c非法词汇的过滤器  
 
using system;  
using system.text;  
using system.io;  
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文件中,添加如下代码:  
 
//这个适合多个页一次过处理  
public void application_beginrequest()   
{  
    string path = httpcontext.current.request.path.tolower();  
    string[] paths = new string[]  
    {  
        "/aa/","/bb/" 
    };  
    foreach (string item in paths)  
    {  
        if (path.startswith(item))  
        {  
            response.filter = new responsefilter(response.filter);  
            break;  
        }  
    }  
}  
 
或者重写某页的render方法   
 

protected override void render(htmltextwriter writer)  
{  
    stringwriter strwriter = new stringwriter();  
    base.render(new htmltextwriter(strwriter));  
    string html = strwriter.tostring();  
    html = util.replaceinvalidkeyword(html);  
    writer.write(html);  

热门栏目