我有以下代码,并发现Server.GetLastError
中表示的文本值
包含单引号并中断我的SQL插入代码。
Exception ex = Server.GetLastError();
StringBuilder theBody = new StringBuilder();
theBody.Append("Error Message: " + ex.ToString() + "\n");
Server.ClearError();
try
{
string sSQL = "INSERT INTO PMISwebErr VALUES ('" + theBody.ToString() + "', GETDATE())";
using (System.Data.SqlClient.SqlConnection con = STAR.Global.GetConnection())
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteScalar();
}
}
catch (Exception exe) {
Response.Redirect("~/default.aspx?Err="+ exe.Message.ToString() );
}
答案 0 :(得分:2)
欢迎来到SQL注入攻击的精彩世界......
选项1:搜索并替换theBody.ToString(),将“'”替换为“''”
选项2:rewrite your SQL command to use parameters。
而且,仅仅因为,你需要check this link。
答案 1 :(得分:2)
string sSQL = "INSERT INTO PMISwebErr VALUES (@errVal, GETDATE())";
using (System.Data.SqlClient.SqlConnection con = STAR.Global.GetConnection())
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue( "@errVal", theBody.ToString() );
cmd.ExecuteScalar();
}
您应该始终在SQL语句中使用参数。它不仅处理诸如带单引号的字符串之类的情况,而且还有助于保护您免受SQL注入攻击。