If you can't filter the Textbox, you have to filter the data in the Postback .
- Use Server.HtmlEncode(your text here) to Escape characters
normally used for SQL Injection :
string userInput = @"' or 1=1; -- ";
string encodedString = Server.HtmlEncode(userInput);
the result will be :
' or 1=1; -- <html>
- Use Regex to replace invalid characters with space or anything to
indicate that the characters was replaced (use *) :
Regex myRegex = new Regex("[\\\'\\\"\\<\\>=]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string userInput = @"' or 1=1; -- <html>";
string encodedString = myRegex.Replace(userInput, "");
the result will be :
or 11; -- html
- Use parameters in your SQL queries and validate the values before add
the
using (SqlConnection cn = new SqlConnection("Your Connection string here"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From [User] Where (UserName = @UserName AND Password = @Password)";
cmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = Server.HtmlEncode(txtUserName.Text);
cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = Server.HtmlEncode(txtPassword.Text);
cn.Open();
IDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
// Your code here
}
}
}
- There is custom controls ready to use with options to control what the user can enter in specified text box .
- Last advice in Web programming you have to double check (1- Client side using JavaScript) and (2- Server side using your own rules of doubts and concerns).