Using .Net ASHX Handlers To Build Web Services

By | 2016-04-21T10:04:11+00:00 February 8th, 2013|Categories: Web Development|Tags: , , , |

Est. Reading Time: 2 minute

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.

About the Author:

James Kite
James has served as the Senior Transactional Developer since July 2012, adding more than 15 years of overall IT experience to the Beacon team. He specializes in .Net and Sql Servers and has a strong knowledge of Cascade Server development, as well as Velocity programming. James holds a B.A. in Computer Information Systems from High Point University.