手机
当前位置:查字典教程网 >编程开发 >asp.net教程 >asp.net 防止SQL注入攻击
asp.net 防止SQL注入攻击
摘要:只要做到以下三点,网站就会比较安全了而且维护也简单。一、数据验证类复制代码代码如下:parameterCheck.cspublicclass...

只要做到以下三点,网站就会比较安全了而且维护也简单。

一、数据验证类

复制代码 代码如下:

parameterCheck.cs

public class parameterCheck{

public static bool isEmail(string emailString){

return System.Text.RegularExpressions.Regex.IsMatch(emailString, "['w_-]+(.

['w_-]+)*@['w_-]+(.['w_-]+)*.[a-zA-Z]{2,4}");

}

public static bool isInt(string intString){

return System.Text.RegularExpressions.Regex.IsMatch(intString ,"^(d{5}-d{4})|

(d{5})$");

}

public static bool isUSZip(string zipString){

return System.Text.RegularExpressions.Regex.IsMatch(zipString ,"^-[0-9]+$|^[0-9]

+$");

}

}

二、Web.config

在你的Web.config文件中,在下面增加一个标签,如下:

复制代码 代码如下:

<appSettings>

<add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-

USzip" />

</appSettings>

其中key是后面的值为“OrderId-int32”等,其中“-”前面表示参数的名称比如:OrderId,后面的int32表示数据类型。

三、Global.asax

在Global.asax中增加下面一段:

复制代码 代码如下:

protected void Application_BeginRequest(Object sender, EventArgs e){

String[] safeParameters = System.Configuration.ConfigurationSettings.AppSettings

["safeParameters"].ToString().Split(',');

for(int i= 0 ;i < safeParameters.Length; i++){

String parameterName = safeParameters[i].Split('-')[0];

String parameterType = safeParameters[i].Split('-')[1];

isValidParameter(parameterName, parameterType);

}

}

public void isValidParameter(string parameterName, string parameterType){

string parameterValue = Request.QueryString[parameterName];

if(parameterValue == null) return;

if(parameterType.Equals("int32")){

if(!parameterCheck.isInt(parameterValue)) Response.Redirect("parameterError.aspx");

}

else if (parameterType.Equals("double")){

if(!parameterCheck.isDouble(parameterValue)) Response.Redirect("parameterError.aspx");

}

else if (parameterType.Equals("USzip")){

if(!parameterCheck.isUSZip(parameterValue)) Response.Redirect("parameterError.aspx");

}

else if (parameterType.Equals("email")){

if(!parameterCheck.isEmail(parameterValue)) Response.Redirect("parameterError.aspx");

}

}

以后需要修改的时候大家只修改以上三个文件就可以了,整个系统的维护效率将会提高,当然你也可以根据自己的需要增加其它的变量参数和数据类型等等。

【asp.net 防止SQL注入攻击】相关文章:

asp.net+js实现的ajax sugguest搜索提示效果

asp.net(C#) Xml操作(增删改查)练习

asp.net neatUpload 支持大文件上传组件

asp.net中C++单例实现问题分析

asp.net下实现URL重写技术的代码

asp.net连接数据库读取数据示例分享

asp.net GridView 中增加记录的方法

asp.net 文章内容分页显示的代码

asp.net操作xml增删改示例分享

asp.net下判断用户什么时候离开,以什么方式离开

精品推荐
分类导航