Are there any thoroughly tested .NET libraries out there to sanitize input from things like script/sql injection?
-
this should be 2 different questions – fretje Jun 02 '09 at 12:14
-
8@fretje, it's only two different questions if you already know that there isn't a library that does both. – DevinB Jun 02 '09 at 12:20
-
sanitizing input against sql injection attacks (usually done at the database level through using parameterised commands) is a total different ballpark than sanitizing input against xss attacks (usually done BEFORE saving the input in the database)... – fretje Jun 02 '09 at 13:49
-
Does this answer your question? [AntiXSS in ASP.Net Core](https://stackoverflow.com/questions/37923431/antixss-in-asp-net-core) – Michael Freidgeim May 03 '21 at 22:50
5 Answers
I like to use the Microsoft AntiXSS library. It's free and pretty easy to use.
For SQL injection, I always use parameters. Again, they are easy to use and I don't like trying to escape special characters. It's a recipe for disaster if you ask me.

- 1,270
- 1
- 11
- 22
SQL injection and Cross-Site Scripting (a.k.a. XSS or Script Injection) are different problems.
1) SQL Injection is very easy, always use parametrized queries (SQLParameter) and try really hard to NEVER do sp_exec @query within T-SQL stored procedures. .Net parametrized queries will not protect against this second order injection.
2) XSS is more difficult to universally mitigate since there are so many places that JavaScript can be inserted into HTML documents. The recommendations to use AntiXSS for encoding user data is right on. Use this library before inserting user data into output documents. Unfortunately, if you are using ASP.Net server controls encoding all data may lead to double-encoding and display artifacts. This happens because some control properties encode data while others don't. Refer to this table to find out the properties encoded by default. Use Anti-XSS before assigning to any properties that don't encode.

- 546
- 2
- 4
Use parameterised commands, rather than trying to sanitize strings, to guard against SQL Injection.

- 295,962
- 43
- 465
- 541
If you are using ASP.NET 4.5 you can now use the AntiXSS features that ship in the framework.
These are the portions of the external AntiXSS Library that have been incorporated into ASP.NET 4.5:
HtmlEncode
,HtmlFormUrlEncode
, andHtmlAttributeEncode
XmlAttributeEncode
andXmlEncode
UrlEncode
andUrlPathEncode
(new)CssEncode

- 13,061
- 11
- 72
- 113
-
Need to include `System.Web.dll` and `using System.Web;` and `using System.Web.Security.AntiXss;`. – Hp93 May 12 '23 at 09:31