ASP.NET HTML encoding attributes in server controls

Did you know that asp.net will html encode your server control attributes as from .NET 4.0? This is done for security reasons and prevent cross site scripting attacks. Going forward, you will need to work around this if the need arises as a security enhancement is more likely not to be backwards compatible.

I came across this “problem” when I was trying to build a degradable web app. When javascript is turned off, everything would work as it’s supposed to (through postbacks) but is JS is enabled, then JQuery will kick in. For this to work, I needed to provide an OnClientClick function to the asp.net buttons. It works fine until you try to insert parameters (arguments) in the javascript function. Since javascript parameters are enclosed with apostrophes, you will find the rendered html quite different from what you entered in the code behind. Take for example the following:


btnSubmit.OnClientClick = String.Format("PostContent('{0}', '{1}', '{2}');", "6", _question.Id, "0");

This will be rendered as:

<input type="submit" name="btnSubmit" value="Submit" onclick="PostContent(&#39;6&#39;, &#39;10112&#39;, &#39;0&#39;);" id="btnSubmit" />

The attribute value has been html encoded. If you view the html source code, you will see that the apostrophe has been converted to ‘&#39;’ Now that’s not really a problem as your javascript functions will still work as normal. However it just looks a bit weird! If you want to change that behaviour of asp.net to html encode server control properties, then you will need to create a class as follows:

public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
 {
 protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
 {
 output.Write(value);
 }
 }

And in your web.config file:

<httpRuntime encoderType="HtmlAttributeNoEncoding"/>

It’s probably worth doing that if you need backwards compatibility with the previous .net frameworks (prior to .net 4.0).

1 Response

  1. Veibert Pinontoan March 21, 2011 / 2:36 am

    Hi, i’m interesting to implement these method. But, i have difficulties on how to put these class on my code. FYI, i’m using MVC

Comments are closed.

comments powered by Disqus