As always my posts are usually based on experiencing some travesty of code that required me either to change or endure it. In this case I was looking at a web page who’s only purpose was to return data … for the more seasoned among us the preceding sentence should scream murder. The truth is a web page has a metric ton of overhead and simply using them as conduits for the delivery of raw unformatted non html information (jpeg, text,xml, etc) is a pure waste of resources. The following is an example of what not to do when you trying to return data:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class WebPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.ContentEncoding = Encoding.UTF8;

        string xml = GetXMLString(); //Not interested in the details

        Response.Write(xml);

    }

}

This example takes advantage of the generic handler, which has all the flexibility of a web page but none of the overhead of the web page life cycle. While I am returning text/xml this could be any of your defined MIME types.

<%@ WebHandler Language="C#" Class="SomeHandler" %>

using System;
using System.Web;
using System.Text;

public class SomeHandler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/xml";
        context.Response.ContentEncoding = Encoding.UTF8;

        string xml = GetXMLString(); //Not interested in the details
        context.Response.Write(xml);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

In my humble opinion the above concept should be known to all senior asp.net developers, in fact this is one of the first interview questions I ask.

Technorati Tags: ,


Comment Section

Comments are closed.