ASP.NET Web Forms Extensibility: Output Encoders

Since version 4, ASP.NET offers an extensible mechanism for encoding the output. This is the content that will be returned to the browser. I already refered it in Providers.

A base class exists, HttpEncoder, for which it used to be the default implementation. It has the responsibility to encode all contents sent to the server, in a differentiated manner – JavaScript is encoded in a way, HTML in another, URLs in another, and so on. Since ASP.NET 4.5, the default implementation is AntiXssEncoder. Those familiar with Anti-Cross Site Scripting Library (now Web Protection Library) will recognize this class, which offers better protection against cross site scripting attacks.

This class offers a number of virtual methods that you can override to change the default behavior: HeaderNameValueEncode (for encoding headers sent in the response), HtmlAttributeEncode (for tag attributes), HtmlEncode (for generic text content), JavaScriptStringEncode (for JavaScript), UrlEncode (URLs) and UrlPathEncode (URL parts). Do create a dummy encoder and debug through these methods to see what they are called with.

The actual implementation to use can be configured by code or XML configuration (the Web.config file).

For using code configuration, one has to change the HttpEncoder.Current in at most the Application_Start event, after that it will be too late:

   1: protected void Application_Start()
   2: {
   3:     HttpEncoder.Current = new MyEncoder();
   4: }

The default implementation is always available in the read only property HttpEncoder.Default.

If you prefer to change the Web.config file, you need to set the encoderType attribute of the httpRuntime section:

   1: <httpRuntime encoderType="MyEncoder, MyAssembly"/>

It is a nice addition, especially together with the validation provider model introduced with ASP.NET 4, which will be the topic of my next post on ASP.NET Web Forms extensibility.

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website