OWASP is the oldest library out there for preventing this or any other kind of malicious user inputs, for your case here is the page you need to go over.
Here is an example
var sanitizer = new HtmlSanitizer();
var html = @"<script>alert('xss')</script><div onload=""alert('xss')"""
+ @"style=""background-color: test"">Test<img src=""test.gif"""
+ @"style=""background-image: url(javascript:alert('xss')); margin: 10px""></div>";
var sanitized = sanitizer.Sanitize(html, "http://www.example.com");
Assert.That(sanitized, Is.EqualTo(@"<div style=""background-color: test"">"
+ @"Test<img style=""margin: 10px"" src=""http://www.example.com/test.gif""></div>"));
Please check web application firewall too https://owasp.org/www-community/Web_Application_Firewall
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…