过滤网址和输入框中的特殊字符,防止sql注入

时间:2023-03-10 06:55:31
过滤网址和输入框中的特殊字符,防止sql注入
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.HtmlControls;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. /// <summary>
  11. ///cedar 的摘要说明
  12. /// </summary>
  13. public class cedar:IHttpModule
  14. {
  15. public cedar()
  16. {
  17. //
  18. //TODO: 在此处添加构造函数逻辑
  19. //
  20. }
  21. public void Dispose()
  22. {
  23. }
  24. public void Init(HttpApplication application)
  25. {
  26. application.AcquireRequestState += new EventHandler(application_AcquireRequestState);
  27. }
  28. private void application_AcquireRequestState(object sender, EventArgs e)
  29. {
  30. HttpContext content = ((HttpApplication)sender).Context;
  31. try
  32. {
  33. string sqlErrorPage = "default.html";//转到默认页面
  34. string keyValue = string.Empty;
  35. string requestUrl = content.Request.Path.ToString();
  36. if (content.Request.QueryString != null)
  37. {
  38. foreach (string val in content.Request.QueryString)
  39. {
  40. keyValue= content.Server.UrlDecode(content.Request.QueryString[val]);
  41. if (!processSqlStr(keyValue))
  42. {
  43. content.Response.Write("您访问的页面发生错误,此问题我们已经记录并尽快改善,请稍后再试。<br><a href=""+sqlErrorPage+"" mce_href=""+sqlErrorPage+"">转到首页</a>");
  44. content.Response.End();
  45. break;
  46. }
  47. }
  48. }
  49. if (content.Request.Form != null)
  50. {
  51. foreach(string val in content.Request.Form)
  52. {
  53. keyValue = content.Server.HtmlDecode(content.Request.Form[val]);
  54. if (keyValue == "_ViEWSTATE") continue;
  55. if (!processSqlStr(keyValue))
  56. {
  57. content.Response.Write("您访问的页面发生错误,此问题我们已经记录并尽快改善,请稍后再试。");
  58. content.Response.End();
  59. break;
  60. }
  61. }
  62. }
  63. }
  64. catch (Exception ex)
  65. {
  66. }
  67. }
  68. private bool processSqlStr(string str)
  69. {
  70. bool returnValue = true;
  71. try
  72. {
  73. if (str.Trim() != "")
  74. {
  75. //取得webconfig中过滤字符串
  76. string sqlStr = ConfigurationManager.AppSettings["FilterSql"].Trim();
  77. //string sqlStr = "declare |exec|varchar |cursor |begin |open |drop |creat |select |truncate";
  78. string[] sqlStrs = sqlStr.Split('|');
  79. foreach (string ss in sqlStrs)
  80. {
  81. if (str.ToLower().IndexOf(ss) >= 0)
  82. {
  83. sqlStr = ss;
  84. returnValue = false;
  85. break;
  86. }
  87. }
  88. }
  89. }
  90. catch
  91. {
  92. returnValue = false;
  93. }
  94. return returnValue;
  95. }
  96. }
  97. 在web.config中添加以下:

    <appSettings>
      <add key="FilterSql" value="declare |exec|varchar |cursor |begin |open |drop |creat |select |truncate "/>
     </appSettings>

    <httpModules>
       <add type="cedar" name="cedar"/>
      </httpModules>