SQL 来自 WCF 服务的查询避免了 SQL 查询视图中的注入

SQL Queries from WCF service avoiding SQL Injection in querying a view

我的 类 来自其他项目,这些项目具有 SQL 查询的字符串。

看我的例子

public class OtherClass
{
    myQuery = "SELECT * FROM v_My_View WHERE code = '@code'";
    // I am targeting a view, not a stored procedure
}

我的问题是,如果我在我的 commandText 中使用它并且只是用一个值替换 @code,这个反对 SQL 注入的论据有效吗?

如果它容易受到 SQL 注入的攻击 - 它的其他选择是什么?

我尝试使用

CMD.Parameters.AddWithValue("@code", _obj.code) 

但它毁了我的查询。

我在访问我的存储过程时使用了参数,但在访问我的视图时没有使用。

这是我的主要内容:

public class Main
{
    public DataTable myMethod()
    {
        try
        {
            DataTable myTable = new DataTable("MyDataTable");

            using (SqlCommand CMD = new SqlCommand())
            {
                CMD.Connection = RBOSUtil.DBConnection();
                CMD.CommandType = CommandType.Text;

                // this is the part I used the string from other class
                CMD.CommandText = OtherClas.myQuery.Replace("@code", _obj.code);

                using (SqlDataAdapter DA = new SqlDataAdapter(CMD))
                {
                    DA.Fill(myTable);
                }
            }
        }
        catch
        {
            throw;
        }
        finally
        {
            //close connection
        }

        return myTable;
    }
}

使用这个

 public class Main
    {
        public DataTable myMethod()
        {
            DataTable myTable = new DataTable("MyDataTable");

            try
            {
                using (SqlCommand CMD = new SqlCommand())
                {
                    CMD.Connection = RBOSUtil.DBConnection();
                    CMD.CommandType = CommandType.Text;
                    //this is the part I used the string from other class
                    CMD.CommandText = OtherClas.myQuery;
                    CMD.Parameters.Add("@code", SqlDbType.NVarChar).value = _obj.code;
                    using (SqlDataAdapter DA = new SqlDataAdapter(CMD))
                    {
                        DA.Fill(myTable);
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //close connection
            }
            return myTable;
        }
    }

在尝试之前声明数据表

您不需要在 SQL 语句中将参数名称用引号引起来: myQuery = "SELECT * FROM v_My_View WHERE code = @code";。否则你在做什么对我来说看起来很好。应该可以。

编辑:我对原始问题和 Ravi 的回答感到困惑。不知何故,我错过了问题和第一个答案之间的分隔符。无论如何,要回答最初的问题,是的,使用 String.Replace 将 @code 替换为值会受到 SQL 注入漏洞的影响。

您应该使用 SQL 参数,就像 Ravi 的答案中的代码一样,但您还需要修改查询以删除参数名称两边的引号。