2017-02-02 2 views
0

그래서 WCF는 JSON을 취하고 어떤 이유로 든 XML Infoset으로 변환합니다 (참조 : https://stackoverflow.com/a/5684703/497745 참조). 그런 다음 JsonReaderDelegator를 사용하여이 XML Infoset을 내부적으로 읽습니다 (참조 : https://referencesource.microsoft.com/#System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonReaderDelegator.cs,c0d6a87689227f04 참조).방법 : C# XML InfoSet to JSON

WCF 실행 흐름을 아주 심층적으로 수정하고 있으며, XML Infoset을 원래 JSON으로 되돌려 놓아야합니다.

WCF에서 생성 한 XML Infoset을 가져 와서 원래 JSON으로 변환 할 수있는 .NET 또는 외부 라이브러리가 있습니까?

답변

0

제한적인 수정을 가해 내 시나리오에서 작동하는 답변을 찾았습니다.

이 문서 : https://blogs.msdn.microsoft.com/carlosfigueira/2011/04/18/wcf-extensibility-message-inspectors/은 XML InfoSet으로 만 공개되는 경우에도 원래 WCF로 제공된 JSON을 기록하는 방법을 설명합니다. 이것이 핵심 통찰이었습니다. 특히 MessageToString 구현을 살펴보십시오. 불행하게도,

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 스택에 주입하기 위해 작성한 클래스 internal class MessageFormatInspector : IDispatchMessageInspector, IEndpointBehavior 내에서 실행, 위의 링크에서 MessageToString의 구현을 기반으로 내 코드의 관련 부분입니다 위의 코드는 WCF 메시지 관리자의 컨텍스트 내에서만 작동합니다.

그러나 XML InfoSet이있는 XMLDictionary를 사용할 수 있으며 WCF 자체에서 생성 된 WCF 변환을 역전하고 원본 JSON을 내보낼 수 있습니다.

앞으로 도움이되기를 바랍니다.