一、global.asax
在global.asax中增加下面一段:
Code
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]+$");
}
public static bool isdouble(object expression)
{
return System.Text.RegularExpressions.Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
}
}
Code
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");
}
}
二、web.config
在你的web.config文件中,在<appsettings>下面增加一个标签:如下
<appsettings>
<add key="safeparameters" value="orderid-int32,customeremail-email,shippingzipcode-uszip" />
</appsettings>