I’ve run into this problem before and I didn’t realize it until right now that I never wrote down the solution, hence the post.

The Problem

So if you found yourself trying to use System.Web.HttpUtility, but the only thing that was popping up in intellisense when you typed “System.Web.” was “AspNetHostingPermission, AspNetHostingPermissionAttribute, AspNetHostingPermissionLevel” which is obviously not what you were looking for. Here is a Gotcha!

Not what you wanted.

The Gotcha

You cannot use System.Web.HttpUtility in a static class or static method. So make sure that isn’t what you are doing. Now if you cannot switch what you are working on from a static sense into an instance based sense then there is still hope. You can simply throw together a method in a utilities class that is instance based, instantiate it and use the HttpUtility indirectly. Problem solved.

Why is this how this works? I have no idea, but I am sure there is a good reason for it.

The Code

Here is some code to help you get started on cheating the need for an instance.

public class Utilities
{
 //Instance based method 
 public string HtmlDecode(string s)
 { 
  return HttpUtility.HtmlDecode(s); 
 }

 //Instance based method
 public string HtmlEncode(string s)
 {
  return HttpUtility.HtmlEncode(s);
 }

 //Static based method
 public static string SHtmlDecode(string s)
 {
  return new Utilities().HtmlDecode(s);
 }

 //Static based method
 public static string SHtmlEncode(string s)
 {
  return new Utilities().HtmlEncode(s);
 }
}

Leave a Reply

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