How can I modify incoming JSON to a WCF REST service before it is converted to a Message?
For example, if I submit the following:
{
"Name": "Joe Bloggs",
"Age": 30
}
I’d like all whitespace to be stripped so the packet body is converted to:
{"Name":"Joe Bloggs","Age":30}
I’m trying to work around a problem in System.Runtime.Serialization.Json.XmlJsonReader that I’ve found where JSON is not converted to XML properly if there is any whitespace in the packet. Since I can’t guarantee that all of my clients will send whitespace-free JSON I’d like some kind of pre-processor that will strip whitespace from the JSON before it is passed to XmlJsonReader.
I’ve looked into implementing a custom IDispatchMessageInspector using the AfterReceiveRequest method. but this is too late as the JSON has already been converted to a Message containing incorrect XML. I’d need to modify the JSON before this stage but I can’t find any extensibility points that far back in the process.
If you want to deal with the message before it’s decoded, you’ll need a custom message encoder for that (that’s the component which converts between the bytes in the wire and the message object). You can find more information about custom encoders at http://blogs.msdn.com/b/carlosfigueira/archive/2011/11/09/wcf-extensibility-message-encoders.aspx.
The custom encoder below strips the white spaces from the JSON document. The default writer created by
JsonReaderWriterFactory.CreateJsonWriterdoesn’t do any pretty printing, so that’s essentially what you need.