How to check if string will fire “A potentially dangerous Request.Form value was detected…” error
The ASP.NET class that validates requests is System.Web.CrossSiteScriptingValidation
, and the method you want is IsDangerousString
. Unfortunately, both are marked internal
, so you can't access them directly. You have several options:
Option 1: Call IsDangerousString
via Reflection. However, Microsoft could change the method at any time, which would break your applicaton.
Option 2: Decompile IsDangerousString
and copy it to your own application. See the code below.
Option 3: Call Membership.GeneratePassword
. This returns a password that is guaranteed to pass request validation.
Excerpts from the ASP.NET CrossSiteScriptingValidation
class (via .NET Reflector):
private static char[] startingChars = new char[] { '<', '&' };
internal static bool IsDangerousString(string s, out int matchIndex)
{
matchIndex = 0;
int startIndex = 0;
while (true)
{
int num2 = s.IndexOfAny(startingChars, startIndex);
if (num2 < 0)
{
return false;
}
if (num2 == (s.Length - 1))
{
return false;
}
matchIndex = num2;
char ch = s[num2];
if (ch != '&')
{
if ((ch == '<') && ((IsAtoZ(s[num2 + 1]) || (s[num2 + 1] == '!')) || ((s[num2 + 1] == '/') || (s[num2 + 1] == '?'))))
{
return true;
}
}
else if (s[num2 + 1] == '#')
{
return true;
}
startIndex = num2 + 1;
}
}
private static bool IsAtoZ(char c)
{
return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}