使用字符过滤的方法防止ASP.NET网站被注入
在Global.asax文件里面写入代码:
protected void Application_BeginRequest(Object sender, EventArgs e) { StartProcessRequest(); }
private void StartProcessRequest() { try { string getKeys = ""; string sqlErrorPage = "/error"; if (Request.QueryString != null) { for (int i = 0; i < Request.QueryString.Count; i++) { getKeys = Request.QueryString.Keys[i]; string val = Request.QueryString[getKeys]; if (StringHelper.CheckValidationUrl(val) || StringHelper.CheckValidationKeyword(val) || StringHelper.CheckValidationKeywordJS(val)) { Response.Redirect(sqlErrorPage); Response.End(); } } } if (Request.Form != null) { for (int i = 0; i < Request.Form.Count; i++) { getKeys = Request.Form.Keys[i]; if (getKeys == "_VIEWSTATE") continue; string val = Request.Form[getKeys]; if (StringHelper.CheckValidationKeyword(val) || StringHelper.CheckValidationKeywordJS(val)) { Response.Redirect(sqlErrorPage); Response.End(); } } } } catch (Exception ex) { Response.Redirect("/error"); return; } }
StringHelper.cs中的方法参考:
/// <summary> /// 去除符号字符,防止SQL注入(URL) /// </summary> /// <param name="val">检查的对象</param> /// <returns>True:包含非法字符;False:不包含非法字符</returns> public static bool CheckValidationUrl(string val) { string str = "'<>~!$^*();|/\"";//% foreach (char ch in str) { if (val.IndexOf(ch) >= 0) { return true; } } return false; } /// <summary> /// 去除SQL关键字,防止SQL注入 /// </summary> /// <param name="val">检查的对象</param> /// <returns>True:包含SQL关键字;False:不包含SQL关键字</returns> public static bool CheckValidationKeyword(string val) { val = " " + val; string sql = " exec | insert | select | delete | update | count | chr | master | truncate | char | declare | drop | create | and | or ";//|mid string[] sql_c = sql.Split('|'); foreach (var sl in sql_c) { if (val.ToLower().IndexOf(sl) >= 0) { return true; } } return false; } /// <summary> /// 去除脚本注入关键字 /// </summary> /// <param name="val"></param> /// <returns></returns> public static bool CheckValidationKeywordJS(string val) { val = " " + val; string sql = " script | alert | href | location "; string[] sql_c = sql.Split('|'); foreach (var sl in sql_c) { if (val.ToLower().IndexOf(sl) >= 0) { return true; } } return false; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2016-03-11 从一个集合中过滤另一个集合中存在的项(类似in)