这是Sql注入证明Asp.net代码吗?

问题描述 投票:1回答:2

有人能告诉我这段代码的优缺点吗?我知道我可以使用存储过程,但是考虑到我有一个文本框,管理员可以输入这个代码,SQL会很容易注入这个代码吗?

string commentId = a.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString);
con.Open();
string sql = "DELETE FROM Comment WHERE Comment.commentId = @commentid";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@commentid", commentId);

cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
c# asp.net
2个回答
2
投票

是的,它看起来很好,因为你正在使用参数化的SQL。但是,你还没有给你的表一个别名,所以我认为你的sql应该是

DELETE FROM Comment WHERE commentId = @commentid

除了保护您免受SQL注入攻击之外,Sql Server还会知道可以使用不同的参数再次调用此sql,因此可以为其缓存有效的执行计划。

另外,在使用它们之后应始终处置连接。

    string commentId = a.Text;

    using (SqlConnection con = new SqlConnection(ConfigurationManager
                .ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString))
    {
        con.Open();
        string sql = "DELETE FROM Comment WHERE Comment.commentId = @commentid";
        using(SqlCommand cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue("@commentid", commentId);

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
    }

如您所见,这样一个简单的操作有相当多的代码。您可以查看dapper,它将消除很多这些问题。有许多图书馆可以帮助你,这里有偏离主题,但它是一个轻量级,受欢迎的库


0
投票

优点:

  • 好的是你使用的命令参数是sql注入安全的。

缺点:

  • 写得不好。
  • 不使用CRUD功能。始终使用功能执行CRUD操作。
  • 不使用使用块。始终使用block,因此您无需处置连接和命令。您无需手动关闭它。

在DataAccessLayer中使用以下代码。

public void DeleteComment(int commentId)
{
     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString))
        {
            con.Open();
            string sql = "DELETE FROM Comment WHERE Comment.commentId = @commentid";
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                cmd.Parameters.AddWithValue("@commentid", commentId);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }

        } 
}

您也可以在单独的函数中编写连接开放代码。

查看此文章了解更多详细信息:

https://www.codeproject.com/Articles/813965/Preventing-SQL-Injection-Attack-ASP-NET-Part-I

© www.soinside.com 2019 - 2024. All rights reserved.