Asp.net prevent SQL injection method example

Time:2021-12-4

This paper describes the method of preventing SQL injection with asp.net. Share with you for your reference, as follows:

Recently, I took over a project of others and found that there are SQL injection vulnerabilities. I don’t want to change too much code, so I don’t need the parameter method to prevent injection. We can only use the traditional stupid way.

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")
    {
       //I won't write in post mode.
    }
    else
    {
      result = ValidUrlGetData();
    }
    if (result)
    {
      Response. Write ("the data you submitted contains malicious characters!");
      Response.End();
    }
}
/// <summary>
///Get data in querystring
/// </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've added a few here. 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 information about asp.net, readers who are interested can see the special topics on this site:《Summary of asp.net optimization skills》、《Summary of asp.net string operation skills》、《Summary of asp.net operating XML skills》、《Summary of asp.net file operation skills》、《Asp.net Ajax skills summary topic》And《Summary of asp.net cache operation skills》。

I hope this article will help you in ASP. Net programming.