using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using CY.Config; namespace CY_ValidaterHttpModule { /// /// 过滤非法输入,如:防止SQL注入,其他非法输入 /// public class ValidaterHttpModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication context) { context.AcquireRequestState += new EventHandler(context_AcquireRequestState); } private void context_AcquireRequestState(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; //context.Response.Write('1'); //context.Response.End(); //return; try { string getkeys = string.Empty; string sqlErrorPage = "~/RemindError.html";//转向的错误提示页面 string keyvalue = string.Empty; string requestUrl = context.Request.Path.ToString(); //url提交数据 if (context.Request.QueryString != null) { for (int i = 0; i < context.Request.QueryString.Count; i++) { getkeys = context.Request.QueryString.Keys[i]; keyvalue = context.Server.UrlDecode(context.Request.QueryString[getkeys]); if (!FilterSql(keyvalue)) { context.Response.Redirect(sqlErrorPage); context.Response.End(); break; } } } //表单提交数据 if (context.Request.Form != null) { for (int i = 0; i < context.Request.Form.Count; i++) { getkeys = context.Request.Form.Keys[i]; keyvalue = context.Server.HtmlDecode(context.Request.Form[i]); if (getkeys == "__VIEWSTATE") continue; if (getkeys == "__EVENTVALIDATION") continue; if (!FilterSql(keyvalue)) { context.Response.Redirect(sqlErrorPage); context.Response.End(); break; } } } } catch (Exception ex) { } } /// /// 过滤非法关键字,这个可以按照项目灵活配置 /// /// /// private bool FilterSql(string key) { bool flag = true; try { if (!string.IsNullOrEmpty(key)) { //非法字段配置 string sqlStr = WebInfo.Instance.IllegalInput; string[] sqlStrArr = sqlStr.Split('|'); foreach (string strChild in sqlStrArr) { if (key.Trim().ToLower().IndexOf(strChild.Trim().ToLower()) != -1) { flag = false; break; } } } } catch { flag = false; } return flag; } } }