ASP.NETxml

Using HttpHandlers to return XML in ASP.NET

Have you ever had the need to server static XML from your website? Sure you did! If the XML is totally static, then it's pretty simple. You just supply the link to the file and you set your web server to serve and cache your XML data.

However, things are a bit trickier if your XML is a serialized object that needs to be served at runtime. In ASP.NET there is a way to do this in an efficient way using an HTTPHandler. In this post, I will show you how to create such a handler and how to leverage its caching capabilities to ensure you don't hammer your server with requests.

The code for the handler class is attached below:

public class MySuperDuperHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var configService = new ConfigService();
        var page = new OutputCachedPage(new OutputCacheParameters
        {
            Duration = 300, // in seconds
            Location = OutputCacheLocation.Server,
            VaryByParam = "None"
        });
        page.ProcessRequest(HttpContext.Current);
            
        XDocument doc = GetXmlData();
            
        context.Response.ContentType = "text/xml";
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.Expires = -1;
        context.Response.Cache.SetAllowResponseInBrowserHistory(true);

        doc.Save(context.Response.Output); 
    }

    public bool IsReusable
    {
        get { return false; }
    }

   /// <summary>
   /// Code required for server-side caching
   /// </summary>
   private sealed class OutputCachedPage : Page
   {
        private readonly OutputCacheParameters cacheSettings;

        public OutputCachedPage(OutputCacheParameters cacheSettings)
        {
            // Tracing requires Page IDs to be unique.
            ID = Guid.NewGuid().ToString();
            this.cacheSettings = cacheSettings;
        }

        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
            InitOutputCache(cacheSettings);
        }
    }
}

View XMLHttpHandler.cs on GitHub

Because this is a synchronous handler, return False for the IsReusable property so that the handler is not pooled. You need also to remember to enable the handler in the web config to ensure that your website does the right thing. Let's do it then:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <httpHandlers>
       <!-- Simple Handler -->
       <add verb="*" path="*.ashx" 
         type="YourNamespace.MySuperDuperHttpHandler, YourNamespace" />
    </httpHandlers>
  </system.web>
</configuration>

View XMLHttpHandler_webconfig.xml on GitHub

Now, if you try to navigate to any page with a .ashx extension, your handler will manage the request.

I hope you found this useful, but feel free to share any thoughts you have in the comments below!

Web.config changes required to enable the handler

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <httpHandlers>
       <!-- Simple Handler -->
       <add verb="*" path="*.ashx" 
         type="skmHttpHandlers.SimpleHandler, skmHttpHandlers" />
    </httpHandlers>
  </system.web>
</configuration>