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:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'Declare the XML document
Dim xmlDoc As New XmlDocument

'Read the input stream to get incoming SOAP message
Dim sr As New StreamReader(System.Web.HttpContext.Current.Request.InputStream)
Dim sXML As String = System.Web.HttpContext.Current.Server.UrlDecode(sr.ReadToEnd())

'Load the xml document


'Send response back to client
End Sub

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.

Protected Sub SendResponse()
System.Web.HttpContext.Current.Response.ContentType = "text/xml"
Dim sb As New StringBuilder()


End Sub

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.