Algorithm to avoid SQL injection on MSSQL Server from C# code?

后端 未结 2 1069
自闭症患者
自闭症患者 2020-12-01 13:12

What would be the best way to avoid SQL injection on the C#.net platform.

Please post an C# implementation if you have any.

2条回答
  •  时光取名叫无心
    2020-12-01 13:52

    There's no algorithm needed - just don't use string concatenation to build SQL statements. Use the SqlCommand.Parameters collection instead. This does all the necessary escaping of values (such as replacing ' with '') and ensures the command will be safe because somebody else (i.e. Microsoft) has done all the testing.

    e.g. calling a stored procedure:

    using (var connection = new SqlConnection("..."))
    using (var command = new SqlCommand("MySprocName", connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.AddWithValue("@Param1", param1Value);
        return command.ExecuteReader();
    }
    

    This technique also works for inline SQL statements, e.g.

    var sql = "SELECT * FROM MyTable WHERE MyColumn = @Param1";
    using (var connection = new SqlConnection("..."))
    using (var command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@Param1", param1Value);
        return command.ExecuteReader();
    }
    

提交回复
热议问题