/// <summary> /// 把字符串中包含的敏感词替换成别的关键字 /// </summary> /// <param name="s">原字符串</param> /// <param name="oldstr">要查找的敏感词</param> /// <param name="newstr">替换后的关键字</param> /// <returns>新的字符串</returns> private string ChangeSubStr(string s, string oldstr, string newstr) { if (s == null || s == "") return ""; //转为小写 string s1 = s.ToLower(); //获取第一个匹配项的索引值 int i = s1.IndexOf(oldstr); //如果有匹配的(有关键字) while (i != -1) { //截取有敏感词之前的内容 string l = s.Substring(0, i); //截取敏感词之后的内容 string r = s.Substring(i + oldstr.Length); //组合成新的内容 s = l + newstr + r; s1 = s.ToLower(); i = s1.IndexOf(oldstr); } return s; } private void CheckForSQLs(HttpRequest Request, HttpResponse Response) { string[] sql = new string[] { "/*", "*/", "--", "‘", "declare", "select", "into", "insert", "update", "delete", "drop", "create", "exec", "master" }; string[] sqlc = new string[] { "/ *", "* /", "- -", "'", "declare", "select", "into", "insert", "update", "delete", "drop", "create", "exec", "master" }; //Form if (Request.Form.Count > 0) { Type type = typeof(System.Collections.Specialized.NameObjectCollectionBase);// Request.Form.GetType(); PropertyInfo pi = type.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); pi.SetValue(Request.Form, false, null); for (int i = 0; i < Request.Form.Count; i++) { string s = Request.Form[i]; //查询每个敏感词,如果字符里含有敏感词,则替换成中文类型的字符 for (int j = 0; j < sql.Length; j++) s = ChangeSubStr(s, sql[j], sqlc[j]); Request.Form.Set(Request.Form.GetKey(i), s); } pi.SetValue(Request.Form, true, null); } //QueryString if (Request.QueryString.Count > 0) { Type type = typeof(System.Collections.Specialized.NameObjectCollectionBase);// Request.Form.GetType(); PropertyInfo pi = type.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); pi.SetValue(Request.QueryString, false, null); for (int i = 0; i < Request.QueryString.Count; i++) { string s = Request.QueryString[i]; for (int j = 0; j < sql.Length; j++) s = ChangeSubStr(s, sql[j], sqlc[j]); Request.QueryString.Set(Request.QueryString.GetKey(i), s); } pi.SetValue(Request.QueryString, true, null); } //cookie for (int k = 0; k < Request.Cookies.Count; k++) { HttpCookie c = Request.Cookies[k]; if (c.Values.Count > 0) { Type type = typeof(System.Collections.Specialized.NameObjectCollectionBase);// Request.Form.GetType(); PropertyInfo pi = type.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); pi.SetValue(c.Values, false, null); for (int i = 0; i < c.Values.Count; i++) { string s = c.Values[i]; for (int j = 0; j < sql.Length; j++) s = ChangeSubStr(s, sql[j], sqlc[j]); c.Values.Set(c.Values.GetKey(i), s); } pi.SetValue(c.Values, true, null); } Response.Cookies.Set(c); } }
时间: 2024-09-30 14:13:23