How can I avoid SQL injection attacks in my ASP.NET application?

前端 未结 16 2037
死守一世寂寞
死守一世寂寞 2020-11-27 20:16

I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 20:46

    Use parameters! It really is that simple :-)

    Create your queries like this (for MS Sql server with C#):

    SqlCommand getPersons = new SqlCommand("SELECT * FROM Table WHERE Name = @Name", conn); 
    

    Here @Name is the parameter where you want to avoid sql injection and conn is an SqlConnection object. Then to add the parameter value you do the following:

    getPersons.Parameters.AddWithValue("@Name", theName);
    

    Here theName is a variable that contains the name you are searching for.

    Now it should be impossible to do any sql injections on that query.

    Since it is this simple there is no reason not to use parameters.

提交回复
热议问题