Channels ▼

Textbox AutoEncoding Improves Security

Several common web attacks exploit coding flaws of applications. SQL injection, for example, takes place when nefarious input text is attached to a SQL statement and forms a syntactically correct command that exceeds (negatively) the programmer’s expectation, so to speak! If the input text is not constrained and verified, attackers can inject ad hoc text into the statement and completely change the behavior of it. In the end, an innocuous SELECT can become a batch in which a DROP TABLE follows the query.

Another common attack is cross-site scripting, also known as XSS. Cross-site scripting originates from the same bad programming practice as SQL injection-unverified input text. An XSS attack is conducted by injecting malicious script code in the body of a web page. Whenever the browser finds a <script> block, it executes the statements. If the script is placed there by the attacker you have no control over its behavior. Nothing, therefore, prevents the attacker from collecting and uploading all client cookies to an external web site.

There's a simple way to prevent XSS at its root-using encoded text. A common bad practice is using the value of the TextBox's Text property to compose a portion of the page. As a result, if the Text property contains malicious script code, that code executes automatically as the page display. Here is a simple workaround:

string text = HttpUtility.HtmlEncode(TextBox1.Text);

The HtmlEncode method encodes a string for transmission by HTTP. It replaces HTTP unfriendly characters with an ad hoc representation. Angle brackets that wrap HTML tags are in the list. The less-than symbol is replaced with the < macro, whereas the greater-than symbol is changed to >. Encoded this way, any text is displayed as is by any browser and doesn't cause you any further harm.

With 14+ years of development behind me, I think I can say that the average developer is a bit lazy at times. So even a simple task like preprocessing TextBox1.Text with an HTML-encoding method can be a sort of mission-impossible. Thanks to the full OOP support you find in the .NET Framework (specifically, inheritance), you can elegantly solve the issue once forever and make your whole personal framework of components inherently more secure. Do not use the classic, standard TextBox control; instead use this one:

namespace Samples.MyControls  {
    public class TextBox : System.Web.UI.WebControls.TextBox
        public TextBox() {
            AutoEncode = true;

        public bool AutoEncode {
            get {return Convert.ToBoolean(ViewState["AutoEncode"]);}
            set {ViewState["AutoEncode"] = value; }

        public override string Text {
            get {
                if (AutoEncode) 
                    return HttpUtility.HtmlEncode(base.Text);
                    return base.Text;
            set {base.Text = value;}

It is a custom TextBox control that inherits from the base class. It adds a new Boolean property-AutoEncode-and overrides the base Text property. When AutoEncode is set to True (the default setting), the get accessor of the Text property silently and automatically encodes the return value. By simply replacing this control to any sensitive instance of the TextBox control you may have, you inherently gain more security by fending off-by design-any possible XSS attack. The principle of inheritance guarantee is that, in doing so, you don't lose any existing functionality related to the TextBox.

Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant based in Rome, Italy. Dino is a contributing editor to Windows Developer Network and MSDN Magazine, and the author of several books for Microsoft Press including Building Web Solutions with ASP.NET and ADO.NET and Applied XML Programming for .NET. Contact Dino at

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.