ASP. NET Example Method for Preventing SQL Injection

  • 2021-09-20 19:53:24
  • OfStack

In this paper, an example is given to describe the method of preventing SQL injection by ASP. NET. Share it for your reference, as follows:

Recently, I took over a project of others and found that there is SQL injection vulnerability. Because I don't want to change too much code, I don't need that kind of parameter method to prevent injection. I can only use the traditional stupid method.

1. Create a new Global. asax file.

2. Add the following code:


void Application_BeginRequest(object sender, EventArgs e)
{
    bool result = false;
    if (Request.RequestType.ToUpper() == "POST")
    {
       //post I won't write the way. 
    }
    else
    {
      result = ValidUrlGetData();
    }
    if (result)
    {
      Response.Write(" The data you submitted has malicious characters! ");
      Response.End();
    }
}
/// <summary>
///  Get QueryString Data in 
/// </summary>
public static bool ValidUrlGetData()
{
    bool result = false;
    for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
    {
      result = Validate(HttpContext.Current.Request.QueryString[i].ToString());
      if (result)
      {
        break;
      }// If a vulnerability is detected 
    }
    return result;
}
public static string []strs = new string[] {"select","drop","exists","exec","insert","delete","update","and","or","user" };// I just added a few here, so you can add more. 
public static bool Validate(string str)
{
    for (int i = 0; i < strs.Length; i++)
    {
      if (str.IndexOf(strs[i]) != -1)
      {
        return true;
        break;
      }
    }
    return false;
}

For more readers interested in asp. net, please check the topics on this site: "asp. net Optimization Skills Summary", "asp. net String Operation Skills Summary", "asp. net Operation XML Skills Summary", "asp. net File Operation Skills Summary", "asp. net ajax Skills Summary" and "asp. net Cache Operation Skills Summary".

I hope this paper is helpful to everyone's asp. net programming.


Related articles: