先说一个比较笨的逐个过滤法,这里需要根据参数的类型分两个情况来处理:
一.如果参数全为数字:
// 检查字符串是否全为数字
public static bool IsNum(string Str)


{
bool blResult = true;
if (Str == "")
blResult = false;
else

{
foreach (char Char in Str)

{
if (!Char.IsNumber(Char))

{
blResult = false;
break;
}
}
if (blResult)
if (int.Parse(Str) == 0)
blResult = false;
}
return blResult;
}

应用:
string Topicid = Request.QueryString["Topicid"];
if (!IsNum(Topicid))
Server.Transfer("Error.aspx?ErrID=404");
二.如果参数为文本:
// Html转换
public static string htmlstr(string chr)


{
if(chr==null)
return "";
chr=chr.Replace("<","<");
chr=chr.Replace(">",">");
chr=chr.Replace("\n","<br>");
chr=chr.Replace("\"",""");
chr=chr.Replace("'","'");
chr=chr.Replace(" "," ");
chr=chr.Replace("\r","");
return(chr);
}

应用:string strClass = htmlstr(Request.QueryString["ClassName"]);
一个一个文件的做比较麻烦而且还有漏掉的危险,下面是如何从整个系统防止注入:
一、新建一个数据验证类:
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是<saveParameters>后面的值为"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");
}
}


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