In Part 1 we covered setting up the Royal Mail API on their developer portal and getting the credentials needed to use the API. In Part 2 we will create the request and response logging messages that will be useful for debugging in test and production.
Request and Response
For the request message we want to log the headers as well as the body of the message, this is useful for debugging, especially with Royal Mail IT support who will want to know what headers were sent with the request.
I was not interested in the headers coming via the response message, so I haven’t logged them, although you could add this. For the response message I wanted to add something that references back to the request. I have used a guid, but you could use any object.
The Message class holds the entire communication between sender and receiver. So a message is either a Request from the client to the external endpoint, or a response.
Each message can only be consumed or written to once, so we need to copy the message to a MessageBuffer to be able to read it. We therefore leave the referenced message unaffected allowing us to consume the copy.
The Message.ToString() method calls a XmlDictionaryWriter which read the message and write it out as xml string to our log file.
Request Message Log
Using the copy of the message, extract the HTTPRequestMessageProperty headers that we added in the ClientMessageInspector and write them out to the log file with the body of the message.
Response Message Log
Add the guid to the top of the file to reference back to the request message log. Then get the StatusCode from the HttpResponseMessageProperty and write this along with the message body out to the log file.
In the next Post
We will finish off the .Net part of the solution adding classes that will implement IEndpointBehaviour, IClientMessageFormatter and IOperationBehaviour.