It all happens with input that us not properly validated
Input validation is a challenging issue and the primary burden of a solution falls on application developers. However, proper input validation is one of your strongest measures of defense against today's application attacks. Proper input validation is an effective countermeasure that can help prevent XSS, SQL injection, buffer overflows, and other input attacks.
Is not it obviuos some one had to come up with some sort of library that give such functionality?
Here it is:
Microsoft Anti-Cross Site Scripting Library V1.5 is Released!
Tutorial: Microsoft Anti-Cross Site Scripting Library V1.5: Protecting the Contoso Bookmark Page
Validation Application Block: Revealed!