C method to verify that user input information contains dangerous strings
- 2021-01-22 05:18:54
- OfStack
This article illustrates C#'s method of verifying that user input contains dangerous strings. Share with you for your reference. The specific analysis is as follows:
This C# function can be used for backend validation of form input data to determine whether the user has submitted some sql-related hazard injection characters
/// <summary>
/// Checks whether the string entered by the customer is valid , And modify the original string to either a valid string or an empty string
/// When an offensive dangerous string is detected in the customer's input , It returns false, Effective return true .
/// </summary>
/// <param name="input"> The string to detect </param>
public static bool IsValidInput(ref string input)
{
try
{
if (IsNullOrEmpty(input))
{
// If it's null , Is out of
return true;
}
else
{
// Replace single quotation marks
input = input.Replace("'", "''").Trim();
// Detects the offensive danger string
string testString = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
string[] testArray = testString.Split('|');
foreach (string testStr in testArray)
{
if (input.ToLower().IndexOf(testStr) != -1)
{
// Attack string detected , Clear the passed value
input = "";
return false;
}
}
// No attack string detected
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I hope this article is helpful to your C# programming.