Cross-site scripting (XSS) attacks are one of the easiest hacks to do, and usually pretty effective merely because developers do not guard against the threat. It is a pain to have to write Server.HtmlEncode( string ) over and over again, or to go into the DataBindings for a label and customize the DataBinding expression to do this. So instead we created a SecureLabel label. It inherits from System.Web.UI.Label and overrides the Render, adding one line to HtmlEncode the label's text. This way we kept all the designer support for a regular label.
Take the code, put it in a library, and just include the dll in your next project. You can even add it to your component toolbox in VS.NET, so the next time you need a secure label, you can just drag and drop it on the page. Here's the code:
using System.Web;
using System.Web.UI.WebControls;
namespace NorthropGrumman.APEB.StandardWebControls
{
///
/// HTML-encodes text to prevent malicious scripting.
///
public class SecureLabel : System.Web.UI.WebControls.Label
{
public SecureLabel()
{ }
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
this.Text = HttpContext.Current.Server.HtmlEncode(this.Text);
base.Render(writer);
}
}
}