首先在Global.asax.cs里面配置一个 提交事件 不用过滤所有的地址 过滤 GET POST的地址就行了
/// <summary> /// 防止sql注入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_BeginRequest(Object sender, EventArgs e) { //过滤Post参数 string url = this.Request.Url.ToString(); if(this.Request.Form.Count>0) { string filterUrl = FilterUrl(url); if (!url.Equals(filterUrl)) { this.Response.Redirect(filterUrl); } } //过滤Get参数 if(this.Request.QueryString.Count>0) { string filterUrl = FilterUrl(url); if (!url.Equals(filterUrl)) { this.Response.Redirect(filterUrl); } } }
/// <summary> /// 过滤特殊字符 /// </summary> /// <param name="url"></param> /// <returns></returns> private string FilterUrl(string url) { string replaceStr = url; if (!string.IsNullOrEmpty(url)) { replaceStr = replaceStr.ToLower(); replaceStr = replaceStr.Replace("<", ""); replaceStr = replaceStr.Replace(">", ""); replaceStr = replaceStr.Replace("|", ""); replaceStr = replaceStr.Replace(""", ""); replaceStr = replaceStr.Replace("'", ""); replaceStr = replaceStr.Replace("%", ""); replaceStr = replaceStr.Replace(";", ""); replaceStr = replaceStr.Replace("(", ""); replaceStr = replaceStr.Replace(")", ""); replaceStr = replaceStr.Replace("+", ""); replaceStr = replaceStr.Replace("script", ""); replaceStr = replaceStr.Replace("alert", ""); replaceStr = replaceStr.Replace("select", ""); replaceStr = replaceStr.Replace("update", ""); replaceStr = replaceStr.Replace("insert", ""); replaceStr = replaceStr.Replace("like", ""); replaceStr = replaceStr.Replace("applet", ""); replaceStr = replaceStr.Replace("body", ""); replaceStr = replaceStr.Replace("embed", ""); replaceStr = replaceStr.Replace("frame", ""); replaceStr = replaceStr.Replace("html", ""); replaceStr = replaceStr.Replace("iframe", ""); replaceStr = replaceStr.Replace("img", ""); replaceStr = replaceStr.Replace("style", ""); replaceStr = replaceStr.Replace("layer", ""); replaceStr = replaceStr.Replace("link", ""); replaceStr = replaceStr.Replace("ilayer", ""); replaceStr = replaceStr.Replace("meta", ""); replaceStr = replaceStr.Replace("object", ""); } return replaceStr; }
下面是图解: