C# Tips

C# Tip Article

How to check potential XSS characters

Problem

How to check if query string in URL contains potential XSS characters?

Solution

Query string in URL can contain potential XSS characters such as <, >. For example, the following URL shows an example of potential XSS script.

	http://test.com/?<script>alert(document.cookie)</script>
To check dangerous <, > characters, we not only check <, > characters but also need to check various variants of <, > characters as follows.

public static bool HasXssFilterChars(string s)
{
	if (string.IsNullOrEmpty(s)) return false;	
	
	s = s.ToLower();
	return s.Contains("<") || s.Contains(">") || 
		   s.Contains("%3c") || s.Contains("%3e") ||
		   s.Contains("<") || s.Contains(">") ||
		   s.Contains("%ef%bc%9c") || s.Contains("%ef%bc%9e");
}