Author: Taote.com
Source: Taote.com
Note: Please indicate the source when reprinting
to prevent SQL injection. Usually, modifying files one by one is not only troublesome but also risks missing. Let me talk about how to prevent injection from the entire system.
By following the following three steps, I believe the program will be safer and the maintenance of the entire website will become simpler.
1. Data verification category:
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]+$");
}
}
2. Web.config
In your Web.config file, add a tag under <appSettings>: as follows
<appSettings>
<add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-USzip" />
</appSettings>
where the key is <saveParameters> and the following value is "OrderId-int32", etc., where "-" in front represents the name of the parameter, such as: OrderId, and the following int32 represents the data type.
3. Global.asax
Add the following paragraph to 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");
}
}
When modifications are needed in the future, we only need to modify the above three files, which will greatly improve the efficiency of maintaining the entire system. Of course, you can add other variable parameters and data types according to your own needs.