.NET预防SQL注入的简易代码

来源:互联网 发布:超星网络教学平台 编辑:程序博客网 时间:2024/05/12 09:27

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

public class AliceSqlFilter
{

/// <summary>/// 检查/// </summary>/// <param name="sWord">字符串</param>/// <returns>布尔值</returns>public static bool CheckKeyWordAndKeyChar(string sWord){    //关键字    string StrKeyWord = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and|script|function|alert|location|href";    //关键字符    string StrRegex = @"[-|;|,|/|\(|\)|\[|\]|}|{|%|\@|*|!|']";    if (Regex.IsMatch(sWord, StrKeyWord, RegexOptions.IgnoreCase) || Regex.IsMatch(sWord, StrRegex))        return true;    return false;}/// <summary>/// 检查/// </summary>/// <param name="sWord">字符串</param>/// <returns>布尔值</returns>public static bool CheckKeyWord(string sWord){    //关键字    string StrKeyWord = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and|script|function|alert|location|href";    if (Regex.IsMatch(sWord, StrKeyWord, RegexOptions.IgnoreCase))        return true;    return false;}/// <summary>/// 检查/// </summary>/// <param name="sWord">字符串</param>/// <returns>布尔值</returns>public static bool CheckKeyChar(string sWord){    //关键字符    string StrRegex = @"[-|;|,|/|\(|\)|\[|\]|}|{|%|\@|*|!|']";    if (Regex.IsMatch(sWord, StrRegex))        return true;    return false;}/// <summary>/// 替换/// </summary>/// <param name="sWord">字符串</param>/// <returns>字符串</returns>public static string RegexReplace(string sWord){    string StrKeyWord = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and|script|function|alert|location|href";    string StrRegex = "[ ,;'()]";    sWord = Regex.Replace(sWord, StrKeyWord, "");    sWord = Regex.Replace(sWord, StrRegex, "");    return sWord;}

}