views:

437

answers:

2

Consider the requirement to log incoming SOAP requests to an ASP.NET ASMX web service. The task is to capture the raw XML being sent to the web service.

The incoming message needs to be logged for debug inspection. The application already has its own logging library in use, so the ideal usage would be something like this:

//string or XML, it doesn't matter.
string incomingSoapRequest = GetSoapRequest();

Logger.LogMessage(incomingSoapRequest);
  • Are there any easy solutions to capture the raw XML of the incoming SOAP requests?
  • Which events would you handle to get access to this object and the relevant properties?
  • Is there anyway IIS can capture the incoming request and push to a log?
+2  A: 

One way to capture the raw message is to use SoapExtensions.

An alternative to SoapExtensions is to implement IHttpModule and grab the input stream as it's coming in.

public class LogModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += this.OnBegin;
    }

    private void OnBegin(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        HttpContext context = app.Context;

        byte[] buffer = new byte[context.Request.InputStream.Length];
        context.Request.InputStream.Read(buffer, 0, buffer.Length);
        context.Request.InputStream.Position = 0;

        string soapMessage = Encoding.ASCII.GetString(buffer);

        // Do something with soapMessage
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}
nivlam
That won't work very well with UTF-8 encoding, I don't think. Also, are you sure the stream is seekable? Always?
John Saunders
For the input stream, yes. This is what I'm currently using to debug incoming requests and I haven't encountered any problems yet. The response stream however was not seekable. I had to wrap the response stream (original/copy) before I could log that.
nivlam
A: 

There are no easy ways to do this. You will have to implement a SoapExtension. The example at the previous link shows an extension that can be used to log the data.

If you had been using WCF, then you could simply set the configuration to produce message logs.

John Saunders