2012-08-15 28 views
4

我正在爲SOAP服務編寫一個WCF客戶端,該服務返回帶有二進制數據(實際上是PDF文件)的MIME多部分結果。它使用自定義消息編碼器。使用WCF自定義解析多部分消息MessageEncoder

如果我將請求作爲單部分格式發送,服務似乎並不介意,所以我能夠返回結果。我看到的結果有兩個問題:

  • 它似乎只返回多部分消息的第一部分。
  • 我找回的數據不能被我的自定義編碼器解碼。

我曾嘗試利用MTOM結合,但食堂的請求。它無法在內容類型中添加「邊界」參數,因此服務器無法理解請求。

我想我想要的是一個基本的文本SOAP請求,但一個響應解碼MTOM樣式。但是,我不知道如何設置它。

我已經發現的最接近的解決方案是這樣的:http://blogs.msdn.com/b/carlosfigueira/archive/2011/02/16/using-mtom-in-a-wcf-custom-encoder.aspx

但它似乎是一個非常激進的變化到我的項目。

回答

5

我想通了。首先,當我說我只使用MTOM編碼器獲得多部分信息的第一部分時,我是不正確的;我得到了整件事情。我正在調試器中查看它,並且底部必須已經在調試查看器中被截斷。根據我的經驗,手動查看和解密多部分消息。

第二點,我所要做的就是在Content-Type爲multipart/related時使用MTOM編碼器,並且一切正常。如果您閱讀了上面的參考文章,則只需動態檢測消息是多部分還是常規文本,然後根據該文本選擇合適的編碼器。實質上,它是一種自定義編碼器,它內置了文本編碼器和MTOM編碼器,並根據傳入消息的內容類型來回切換。

我們的項目在交給主程序邏輯之前需要對響應消息進行一些後處理。因此,我們將傳入的SOAP內容作爲XML字符串進行處理,並對其進行一些XML操作。

這與本文推薦的解決方案略有不同。本文解決方案中所需的全部內容是使用正確的編碼器將消息讀入System.ServiceModel.Channels.Message並返回。在我們的解決方案中,我們需要中斷這個過程並進行後期處理。

要做到這一點,實現您的自定義編碼器執行以下操作:

public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType) 
{ 
    //First, get the incoming message as a byte array 
    var messageData = new byte[buffer.Count]; 
    Array.Copy(buffer.Array, buffer.Offset, messageData, 0, messageData.Length); 
    bufferManager.ReturnBuffer(buffer.Array); 
    //Now convert it into a string for post-processing. Look at the content-type to determine which encoder to use. 
    string stringResult; 
    if (contentType != null && contentType.Contains("multipart/related")) 
    { 
     Message unprocessedMessageResult = this.mtomEncoder.ReadMessage(buffer, bufferManager, contentType); 
     stringResult = unprocessedMessageResult.ToString(); 
    } 
    else { 
     //If it's not a multi-part message, the byte array already has the complete content, and it simply needs to be converted to a string 
     stringResult = Encoding.UTF8.GetString(messageData); 
    } 
    Message processedMessageResult = functionToDoPostProccessing(stringResult); 
    return processedMessageResult; 
} 
+0

不要忘了,這是確定以紀念自己的答案是正確的 - http://meta.stackexchange.com/questions/ 9933 /存在,-A-約定換受理 - 我 - 自己的回答對我 - 擁有 - 問題 – 2012-08-17 17:22:16