We again leverage Hacme Books for an example vulnerable code.
We fix this using output encoding method. Here we use Struts bean:write tag that supports output filtering of dangerous characters in the HTTP Response by default.
ASP.Net
Below is a vulnerable code Hacme Bank.
string messageSubject = txtSubject.Text;
string messageText = txtText.Text;
Here txtSubject.Text and txtText.Text could be injected with malicious code.
However if we use Microsoft Anti-Cross Site Scripting Library the malicious code would be encoded when displayed to a victim and hence rendered harmless.
string messageSubject = AntiXss.HtmlEncode(txtSubject.Text);
string messageText = AntiXss.HtmlEncode(txtText.Text);
Again we allowed the application to accept malicious input in first place. If threat profiling of use cases necessitate, ASP.Net in-built validation routine called RegularExpressionValidator could be leveraged to filter the unwanted input.
The example below enforces txtSubject.Text and txtText.Text to accept alphabets and numbers only.