通过一些有限的修改,找到了适用于我的场景的答案。
这篇文章:https ://blogs.msdn.microsoft.com/carlosfigueira/2011/04/18/wcf-extensibility-message-inspectors/解释了如何记录最初进入 WCF 的 JSON,即使它只是公开的作为 XML 信息集。这是关键的见解。具体来说,看看它的 MessageToString 实现。
下面是我的代码的相关部分,基于上面链接中 MessageToString 的实现,在internal class MessageFormatInspector : IDispatchMessageInspector, IEndpointBehavior
我编写的注入 WCF 堆栈的类中运行:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
...
var s = GetJsonFromMessage(request);
...
}
private static string GetJsonFromMessage(ref Message request)
{
using (MemoryStream ms = new MemoryStream())
{
using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(ms))
{
request.WriteMessage(writer);
writer.Flush();
string json = Encoding.UTF8.GetString(ms.ToArray()); //extract the JSON at this point
//now let's make our copy of the message to support the WCF pattern of rebuilding messages after consuming the inner stream (see: https://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.idispatchmessageinspector.afterreceiverequest(v=vs.110).aspx and https://blogs.msdn.microsoft.com/carlosfigueira/2011/05/02/wcf-extensibility-message-formatters/)
ms.Position = 0; //Rewind. We're about to make a copy and restore the message we just consumed.
XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max); //since we used a JsonWriter, we read the data back, we need to use the correlary JsonReader.
Message restoredRequestCopy = Message.CreateMessage(reader, int.MaxValue, request.Version); //now after a lot of work, create the actual copy
restoredRequestCopy.Properties.CopyProperties(request.Properties); //copy over the properties
request = restoredRequestCopy;
return json;
}
}
}
不幸的是,上面的代码只能在 WCF 消息检查器的上下文中工作。
但是,它可以使用具有 XML InfoSet 的 XMLDictionary,并使用 WCF 自己内置的 JsonWriter 来反转 WCF 所做的转换并发出原始 JSON。
我希望这可以帮助某人在将来节省一些时间。