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:
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:
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>