我可以在用户输入上使用asp.net验证器来避免sql注入攻击吗

本文关键字:sql 攻击 注入 验证 net 输入 用户 asp 我可以 | 更新日期: 2023-09-27 18:21:27

我正在设计一个网站,用户指定一个帐户ID(必须是8位数字),以便查找与该帐户相关的计费日期。我使用了asp.net正则表达式验证器来防止用户输入字符。我还在这个文本框中附加了一个必需的字段验证器。

我已经阅读了其他stackoverflow问题中关于SQL注入攻击的内容,但我没有遇到任何与使用验证器保护查询有关的内容。

有了这些验证器,我有什么理由担心sql注入攻击吗?我还需要(或应该)做些什么来防止恶意用户滥用这个用户输入吗。

以下是我的C#代码,用于SQL查询,并用与AccountID:相关的账单周期日期填充下拉列表

string sqlCommandString = "SELECT StatementDate AS StateDate FROM dbTable " + 
    "WHERE AccountID = '" + AccountID + "' ORDER BY StatementDate DESC";
string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
{
    sqlConnection.Open();
    DropDownList_StatementDate.DataSource = sqlCommand.ExecuteReader();
    DropDownList_StatementDate.DataBind();
}

这里是我使用的正则表达式验证器:

<asp:RegularExpressionValidator
    ID="RegExpVal_AccountID"
    runat="server"
    ErrorMessage="Must be 8 digits"
    ValidationExpression="^'d{8}$"
    ControlToValidate="TextBox_AccountID"
    CssClass="ValidatorStyle"
    Display="Dynamic">        
</asp:RegularExpressionValidator>

谢谢。

我可以在用户输入上使用asp.net验证器来避免sql注入攻击吗

只需使用参数化查询(防止SQL注入攻击的唯一安全方法):

string sqlCommandString = "SELECT StatementDate AS StateDate FROM dbTable " + 
    "WHERE AccountID = @AccountID ORDER BY StatementDate DESC";
string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
{
    sqlConnection.Open();
    sqlCommand.Parameters.AddWithValue("@AccountID", AccountID);
    DropDownList_StatementDate.DataSource = sqlCommand.ExecuteReader();
    DropDownList_StatementDate.DataBind();
}