防止sql注入及恶意输入
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
/// <summary>
///UserHelper 的摘要说明
/// </summary>
public class UserHelper
{
public UserHelper()
{
/// <summary>
/// 此方法用于确认用户输入的不是恶意信息
/// </summary>
/// <param name="text">用户输入信息</param>
/// <param name="maxLength">输入的最大长度</param>
/// <returns>处理后的输入信息</returns>
public static string InputText(string text, int maxLength) {
text = text.Trim();
if (string.IsNullOrEmpty(text))
return string.Empty;
if (text.Length > maxLength)
text = text.Substring(0, maxLength);
//将网页中非法和有攻击性的符号替换掉,以防sql注入!返回正常数据
text = Regex.Replace(text, "[\\s]{2,}", " "); // 2个或以上的空格
text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br> html换行符
text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); // html空格符
text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); // 任何其他的标签
text = text.Replace("'", "''");// 单引号
return text;
}
// 对这个Regex.Replace方法说明一下:
// public static string Replace(string input, string pattern, string replacement);
// 摘要:
// 从输入字符串中的第一个字符开始,用替换字符串替换由正则表达式定义的匹配的所有匹配项。
//
// 参数:
// pattern:
// 要匹配的正则表达式模式。
//
// input:
// 要修改的字符串。
//
// replacement:
// 替换字符串。
//
// 返回结果:
// 已修改的字符串。
/// <summary>
/// 此方法用于检查用户输入除了数字是否包含其他
/// </summary>
public static string CleanNonWord(string text) {
return Regex.Replace(text, "\\W", "");
}
}
}
浙公网安备 33010602011771号