0

因此,WCF 采用 JSON,并且无论出于何种原因将其转换为 XML 信息集(请参阅:https ://stackoverflow.com/a/5684703/497745 )。然后,它使用 JsonReaderDelegator 在内部读回此 XML 信息集(请参阅:https ://referencesource.microsoft.com/#System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonReaderDelegator.cs,c0d6a87689227f04 )。

我正在对 WCF 执行流程进行一些非常深入的修改,我需要将 XML Infoset 反转回原始 JSON。

.NET 或外部是否有可以获取 WCF 生成的 XML 信息集并将其转换回其原始 JSON 的库?

4

1 回答 1

0

通过一些有限的修改,找到了适用于我的场景的答案。

这篇文章: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。

我希望这可以帮助某人在将来节省一些时间。

于 2017-02-03T02:03:29.443 回答