Friday, April 21, 2006

Getting at HttpServerUtility

Here's the problem - you want to HTML encode some content in a class library that supports your ASP.Net application... You could write the routine to HTML encode a string yourself, or you could re-factor your code to do the encoding in the page code-behind like this:
public partial class DemoPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LabelControl.Text =
Server.HtmlEncode( LibraryClassInstance.Content );
}

// rest of the implementation goes here
}
But what if you're abstracting things so that a library object has to be able to render itself as HTML?

The problem is all about getting at the HtmlEncode method if you've not got a Server object handy. The Server object is actually a singleton instance of the HttpServerUtility class exposed by the ASP.Net environment from the HttpContext in which the page is running.

HOWEVER, the HttpContext class exposes a static method to return the current context instance, including the associated HttpServerUtility instance, so all you have to do in the library is the following
namespace demo
{
class LibraryClass
{
public string GetHtmlSafeContent()
{
return HttpContext.Current.Server.HtmlEncode(this.Content);
}

// remainder of the implementation goes here
}
}
Voila - HTML (and URL) encoding and de-coding at your fingertips.

No comments: