Introduction
An application is susceptible to XSS vulnerability if 'user input' is returned back to the browser client without being validated or escaped. If the user enters a malicious input (script) instead of a legitimate input then that malicious input (script) can be executed by the browser client when returned. For brevity, the 'user input' when returned back from the server is referred to as 'returned input' in this article.
In order to holistically mitigate the XSS vulnerability, we have to apply all of the following controls:
Validate user input (Input Validation)
- Use a whitelist of legitimate 'user input' to validate on the client-side as well as on the server side.
- Validate all headers, cookies, URL querystring values, form fields, and hidden fields.
- Validate the length, datatype and any bussiness rule for the 'user input'
- Set 'validateRequest' flag to 'true' either at the application level (web.config file as illustrated below) or at page level
- <configuration>
- <system.web>
- <pages validateRequest="true" />
- </system.web>
- </configuration>
Saving 'user input' to database in the controller of ASP.NET MVC 4
The following snippet uses the whitelist of a set of allowed characters making it more secure as compare to the default encoder of ASP.NET.- Comment comment = new Comment();
- comment.usercomment = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(form[“usercomment”],false);
- db.Comments.Add(comment);
- db.SaveChanges();
- comment.usercomment=server.Html.Encoder(form["usercomment"]

Guest UserPosted Jul 4, 2020, 3:13 PM
Great post, great tips.