Re-enable request validation in ASP.NET

by Mads Kristensen 14. October 2007 22:24

Request validation is enabled by default in ASP.NET and it basically stops people from submitting a form with HTML in any of the input fields. It’s a little more sophisticated than that, but basically it just looks for HTML tags and if it finds any, it throws an exception and the form is prevented from being posted.

However, you often want people to be able to write HTML tags in your forms. That’s why most people turn it off either globally in web.config or on the individual pages hosting a form and then just HTML encodes the values. I’ve done it reluctantly myself many times, but there is a smarter way to allow HTML input without turning request validation off.

What if we could just HTML encode all input fields just before the form is submitted? That way we could benefit from request validation and the security it offers out of the box. By having request validation enabled, you also make it impossible for spambots to post links in your form.

The easiest way of doing this is to create a custom server control that inherits from System.Web.UI.WebControls.TextBox and add a little JavaScript magic. I’ve written a SafeTextBox class that HTML encodes its value client-side and then HTML decodes the value again server-side. That way it can be treated just like a normal TextBox.

public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
 protected override void OnLoad(System.EventArgs e)
 {
  base.OnLoad(e);
  if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "TextBoxEncode"))
  {
   System.Text.StringBuilder sb = new System.Text.StringBuilder();
   sb.Append("function TextBoxEncode(id)");
   sb.Append("{");
   sb.Append("var tb = document.getElementById(id);");
   sb.Append("tb.value = tb.value.replace(new RegExp('<', 'g'), '&lt;');");
   sb.Append("tb.value = tb.value.replace(new RegExp('>', 'g'), '&gt;');");
   sb.Append("}");
   Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "TextBoxEncode", sb.ToString(), true);
  }

  // Adds the function call after the form validation is called.
  if (!Page.IsPostBack)
   Page.Form.Attributes["onsubmit"] += "TextBoxEncode('" + ClientID + "');";
 }

 public override string Text
 {
  get { return base.Text; }
  set
  {
   if (!string.IsNullOrEmpty(value))
    base.Text = value.Replace("&lt;", "<").Replace("&gt;", ">");
   else
    base.Text = value;
  }
 }
}

The way the SafeTextBox HTML encodes/decodes is not very sophisticated but it works. You can add your own logic to the encoding/decoding if you feel the need.

To roll this out on your own website, just dump the SafeTextBox class in the App_Code folder and hook it up using tag mapping.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags: , , ,

ASP.NET | Security | Tips and tricks

Comments

10/19/2007 2:00:00 AM #

Andreas

When using the ASP.NET AJAX UpdatePanel it's unfortunately raising an Error when using SafeTextBox

script type="text/javascript"
//<![CDATA[
function TextBoxEncode(id){var tb = document.getElementById(id);tb.value = tb.value.replace(new RegExp('<', 'g'), '&lt;');tb.value = tb.value.replace(new RegExp('>', 'g'), '&gt;');}//]]>
/script

tb is null

Andreas Germany |

10/22/2007 3:32:13 PM #

Einar

Should probably use Page.ClientScript.RegisterOnSubmitStatement, instead of changing the value of the "onsubmit" attribute yourself.

Einar Norway |

10/23/2007 9:37:42 PM #

trackback

Trackback from Csharp Feeds

扩展TextBox控件

Csharp Feeds |

10/25/2007 4:39:09 PM #

pingback

Pingback from andreas-kraus.net

Follow Up: Enable ValidateRequest in ASP.NET and still read HTML - Andreas Kraus: C#, ASP.NET, Silverlight

andreas-kraus.net |

10/26/2007 11:37:17 AM #

White Rose

What will happend if I want to put a value which contains "& lt;" and "& gt;"? (no space between them). They'll be converted to "<" and ">".

White Rose Vietnam |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008