2012-01-25 37 views
3

我有一個帶有SOAP和REST端點的Web服務。我必須接受來自客戶端的請求,而我在REST端點上沒有任何控制權。目前客戶端獲得400響應和我的服務器上的跟蹤日誌顯示了這個錯誤:WCF REST端點可以強制接受原始消息格式嗎?

The incoming message has an unexpected message format 'Raw'. 
The expected message formats for the operation are 'Xml', 'Json'. 

我用盡了一切我能想到的與WebContentTypeMapper但似乎結束了正確的地方,我開始每次。來自客戶端的請求看起來不是格式良好的XML或JSON,因此如果我嘗試從WebContentTypeMapper強制XML或JSON類型,最終會出現分析器錯誤。

所以我想我需要找出是否可以強制這個端點接受消息。這應該很容易,對嗎? ...傢伙? ...對?

回答

8

如果你讓操作使用的是流,那麼你可以自己分析傳入的數據,並制定出什麼與它做。 HTTP請求的內容類型應告訴你什麼是在流

作爲一個例子,假設你有一個服務,允許你上傳圖像。您可能需要根據圖像類型執行不同類型的圖像處理。因此,我們有服務合同如下:

[ServiceContract] 
interface IImageProcessing 
{ 
    [OperationContract] 
    [WebInvoke(Method="POST", UriTemplate = "images")] 
    void CreateImage(Stream stm); 
} 

實施檢查請求的內容類型,並且執行處理依賴於它:

public void CreateImage(Stream stm) 
{ 
    switch(WebOperationContext.Current.IncomingRequest.ContentType) 
    { 
     case "image/jpeg": 
      // do jpeg processing on the stream 
      break; 

     case "image/gif": 
      // do GIF processing on the stream 
      break; 

     case "image/png": 
      // do PNG processing on the stream 
      break; 

     default: 
      throw new WebFaultException(HttpStatusCode.UnsupportedMediaType); 
    } 
} 
+0

你可以擴展這個嗎? – Jacob

+0

增加了一個例子來說明我的意思 –

+0

我現在已經完成了所有工作。謝謝您的幫助。 – Jacob

0

我的理解是,REST需要JSON或XML,點擊這裏:

WCF REST: XML, JSON or Both?

WCF (Windows Communication Foundation) is the new standard for building services with .NET and REST (REpresentational State Transfer) has been a very popular technique when building services and not just in the .NET space. With services, you transport serialized data across the pipe to be worked with and there are a few serialization methods:

Binary: Not for REST services, but provides the smallest packet size. Each end must explicity know how to handle the data.

SOAP: The long running standard for web services. Very descriptive, but a very large packet size due to the amount of meta data.

XML (POX): Plain Old XML provides the just the data with structure without the meta data leaving a smaller packet size.

JSON (JavaScript Object Notation): A new and up coming standard with a similar packet size to a plain XML feed, but can be used directly in JavaScript making it the best option when consuming a service from jQuery.

+0

REST(在純意義上)強加給沒有限制有效載荷格式。然而,WCF中的REST顯然是這樣。 –

相關問題