Using .Net ASHX Handlers To Build Web Services

Est. Reading Time: 2 minutes

I was recently given the task of rewriting an existing web service with a predefined SOAP request and response.  I didn’t have access to the original code to use as a reference point, but it was fairly simple in concept:  Receive an incoming SOAP message, do some processing, and send a SOAP response back to the caller.  Initially, I attempted to use a standard Visual Basic ASMX web service but was unable to get my incoming and outgoing objects to perfectly match the predefined SOAP messages that I was expected to use.  I even tried using Microsoft’s WSDL.exe to reverse engineer the old web service’s WSDL (web service definition language) but still had no luck.

After some head scratching, I finally decided to try a more “brute force” approach using a Microsoft HTTP handler (ASHX) file.  Below is a code sample of accepting an incoming SOAP/XML message with one of these ASHX files and sending a response back to the caller:

As you can see, I am simply taking what is being passed in the input stream and loading it in to an XmlDocument object.  From there I can read the XML and do whatever processing is necessary.  Additionally, I am sending a SOAP response back to the client by simply setting the content type of the response to text/xml and writing out the XML.

By setting up my web service using an HTTP handler, I was able to bypass the mysterious Microsoft “black box” that you encounter when using a standard ASMX to send and receive SOAP messages.  And since this places the incoming and outgoing SOAP messages completely under my control, I am able to easily configure the structure of those messages via code.  So at the end of the day I had a functional, scalable, and easily maintained web service.

James Kite
Web Transactional Developer with Beacon since July 2012, using primarily .NET and Sql Server. James has a Degree in CIS from High Point University. Outside of work he enjoy books, movies, gaming, and spoiling my two Golden Retrievers.
Load More Posts