HTML and URL encoding for SharePoints

MSDN is not really specific when it comes to encoding matters. I wonder why. Working on a SharePoint web portal that must deliver it contents according to the XHTML standard I took a closer look at the encoding methods in the framework.

I got the best result by with the following stategy:

  1. Use HttpUtility.UrlEncode to encode the values (not the keys!) in the querystring.
  2. Use HttplUtility.HtmlEncode to encode the URL before sending it to the client.
  3. In a page receiving the link never use the Querystring property. It does not handle the html encoded querystring correctly (with IE 7.0). Instead use the Params property to extract the querystring values.

Using step 1 is not always necessary. But if your querystring values can contain an ampersand or other characters that will be touched by the HTML encode you need to do it.

SPEncode.HtmlEncode
Seems to do the same HttpUtility.HtmlEncode but definetly on fewer chars.

SPEncode.EncodeAsUrl
Great method to really URL encode a complete URL. Replaces ‘ ‘ by %20 and does not touch http:// for example.

HttpUtility.UrlEncode
Only useful for encoding querystring values. Does not follow any RFC. For example the ‘ ‘ is replaced by a ‘+’ which can cripple you data once i contains ‘+’ characters in the source.

HttpUtility.HtmlEncode
HTML encodes a string. An ‘&’ is transformed to the HTML equivalent ‘&’ and so forth.

Leave a Reply

Your email address will not be published. Required fields are marked *