/// <summary>
/// 检测是否有Sql危险字符
/// </summary>
/// <param name="str">要判断字符串</param>
/// <returns>判断结果</returns>
public static bool IsSafeSqlString(string str)
{
//return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
var returnValue = true;
try
{
if (str.Trim() != "")
{
var sqlStr = "exec|insert+|select+|delete|update|count|chr|mid|master+|truncate|char|declare|drop+|drop+table|creat+|create|*|iframe|script|";
sqlStr += "exec+|insert|delete+|update+|count(|count+|chr+|+mid(|+mid+|+master+|truncate+|char+|+char(|declare+|drop+table|creat+table";
var anySqlStr = sqlStr.Split('|');
var anySqlStrList = new List<string>();
anySqlStrList.AddRange(anySqlStr);
if (anySqlStrList.Contains(str.ToLower()))
{
returnValue = false;
}
}
}
catch
{
returnValue = false;
}
return returnValue;
}
/// <summary>
/// 检查危险字符
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static string Filter(string sInput)
{
if (string.IsNullOrEmpty(sInput))
return null;
string sInput1 = sInput.ToLower();
string output = sInput;
string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
{
throw new Exception("字符串中含有非法字符!");
}
else
{
output = output.Replace("'", "''");
}
return output;
}
/// <summary>
/// 检查过滤设定的危险字符
/// </summary>
/// <param name="word"></param>
/// <param name="inText">要过滤的字符串 </param>
/// <returns>如果参数存在不安全字符,则返回true </returns>
public static bool SqlFilter(string word, string inText)
{
if (inText == null)
return false;
foreach (string i in word.Split('|'))
{
if ((inText.ToLower().IndexOf(i + " ", StringComparison.Ordinal) > -1) || (inText.ToLower().IndexOf(" " + i, StringComparison.Ordinal) > -1))
{
return true;
}
}
return false;
}