EntityFrameWork(以后简称EF)作为一款ORM非常的实用,能够大幅度的提高开发速度,但是EF的实质也是sql语句,同样需要防sql注入,在这里利用过滤器的特性来实现过滤特殊字符。
1.首先是过滤的代码
1 public class SqlFilterAttribute : FilterAttribute, IActionFilter 2 { 3 4 public void OnActionExecuted(ActionExecutedContext filterContext) 5 { 6 throw new NotImplementedException(); 7 } 8 9 public void OnActionExecuting(ActionExecutingContext filterContext) 10 { 11 //获得action的参数 12 var actions = filterContext.ActionDescriptor.GetParameters(); 13 14 //遍历所有的参数 15 foreach (var action in actions) 16 { 17 if (action.ParameterType == typeof(string)) 18 { 19 if (filterContext.ActionParameters[action.ParameterName] != null) 20 { 21 filterContext.ActionParameters[action.ParameterName] = SqlFilter(filterContext.ActionParameters[action.ParameterName].ToString()); 22 } 23 } 24 } 25 } 26 27 private const string SQL_FILTER_STRINGS = "=,',:, or ,select,update,insert,delete,declare,exec,drop,create,%,--"; 28 29 /// <summary> 30 /// 过滤字符串 31 /// </summary> 32 /// <param name="filterStr"></param> 33 /// <returns></returns> 34 private string SqlFilter(string filterStr) 35 { 36 if (!string.IsNullOrEmpty(filterStr)) 37 { 38 foreach (var item in SQL_FILTER_STRINGS.Split(',')) 39 { 40 //替换掉特殊字符 41 filterStr = filterStr.ToLower().Replace(item, ""); 42 } 43 } 44 return filterStr; 45 } 46 }
2.调用sql过滤
public class DefaultController : Controller { // GET: Default public ActionResult Index() { return View(); } [HttpPost] [SqlFilter] public ActionResult Index(string s) { return View(); } }
测试之后发现要求过滤的字符确实被过滤掉了。