---
title: "ASP.NET中如何防SQL注入"
author: "karrykai"
date: "2009-08-05T10:50:28Z"
tags: []
slug: "asp-net-sql"
draft: false
lastmod: "2009-08-05T10:50:28Z"
id: 474385
url: "https://karrykai.iteye.com/blog/474385"
---

防SQL 注入是一个系统工程,在项目开发中就要系统的考虑SQL 注入的问题。一般做到以下4点，能比较好的控制SQL 注入：

1. 严格验证用户的一切输入，包括URL参数。
2. 将用户登录名称、密码等数据加密保存
3. 不要用拼接字符串的方式来生成SQL语句，而是用SQL Parameters 传参数或者用存储过程来查询
4. 严格验证上传文件的后缀，exe、aspx、asp等可执行程序禁止上传。

这里介绍一个简单通用的方法，用来验证字符串中是否有敏感字符，参数可以是一个字符串，也可以是一个字符串集合，敏感字符可以在Lawlesses数组中定义：

01. public static string\[] Lawlesses = { "=", "'" };
02. /// &lt;summary&gt;
03. /// 敏感字符检测
04. /// &lt;/summary&gt;
05. /// &lt;param name="args"&gt;&lt;/param&gt;
06. /// &lt;returns&gt;&lt;/returns&gt;
07. public static bool CheckParams(params object\[] args)
08. {
09. if (Lawlesses == null || Lawlesses.Length &lt;= 0) return true;
10. //构造正则表达式,例:Lawlesses是=号和'号,则正则表达式为 .\*\[=}'].*
11. //另外,由于我是想做通用而且容易修改的函数,所以多了一步由字符数组到正则表达式,实际使用中,直接写正则表达式亦可;
12. string str\_Regex = ".\*[";
13. for (int i = 0; i &lt; Lawlesses.Length - 1; i++)
14. {
15. str\_Regex += Lawlesses\[i] + "|";
16. }
17. str\_Regex += Lawlesses\[Lawlesses.Length - 1] + "].\*";
18. //
19. foreach (object arg in args)
20. {
21. if (arg is string)//如果是字符串,直接检查
22. {
23. if (Regex.Matches(arg.ToString(), str\_Regex).Count &gt; 0)
24. return false;
25. }
26. else if (arg is ICollection)//如果是一个集合,则检查集合内元素是否字符串,是字符串,就进行检查
27. {
28. foreach (object obj in (ICollection)arg)
29. {
30. if (obj is string)
31. {
32. if (Regex.Matches(obj.ToString(), str\_Regex).Count &gt; 0)
33. return false;
34. }
35. }
36. }
37. }
38. return true;
39. }

 

参考文档：[http://msdn.microsoft.com/zh-cn/library/ms998271(en-us).aspx](http://msdn.microsoft.com/zh-cn/library/ms998271%28en-us%29.aspx)

Copyright [playgoogle.com](http://www.playgoogle.com)© 2008

[继续阅读《ASP.NET中如何防SQL注入》的全文内容...](http://www.playgoogle.com/post/95.html)

### 相关文章:

- [ASP.NET 缓存技术](http://www.playgoogle.com/post/12.html)  (2008-7-12 8:43:57)

* * *

### 最新评论:

- [2009-8-22 3:44:25](http://www.playgoogle.com/post/95.html#cmt232)，xmq120 ： 需要这样吧 用3层开发 问题完全不存在

![](http://www1.feedsky.com/t1/271665528/PlayGoogleKarry/feedsky/s.gif?r=http%3A%2F%2Fwww.playgoogle.com%2Fpost%2F95.html)

[![](http://www1.feedsky.com/r/i/feedsky/PlayGoogleKarry/271665528/art01.gif)](http://www1.feedsky.com/r/l/feedsky/PlayGoogleKarry/271665528/art01.html)