2010-09-23 45 views
30

this位置下載了WCF REST模板。WCF 4.0:WebMessageFormat.Json不能與WCF REST模板一起使用

默認的響應格式是XML,這很好用。但是,當我嘗試獲得JSON響應時,我仍然獲得XML。

這是我修改後的代碼 -

[WebGet(UriTemplate = "",ResponseFormat = WebMessageFormat.Json)] 
    public List<SampleItem> GetCollection() 
    { 
     // TODO: Replace the current implementation to return a collection of SampleItem instances 
     return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } }; 
    } 

注意ResponseFormat = WebMessageFormat.Json。這是我對該模板做的唯一改變。

我錯過了什麼?

謝謝!

回答

56

想通了。 automaticFormatSelectionEnabled standardendpoint的屬性應設置爲false,並且defaultOutgoingReponseFormat應設置爲Json

<standardEndpoint name="" helpEnabled="true" 
    automaticFormatSelectionEnabled="false" 
    defaultOutgoingResponseFormat ="Json" /> 
+0

我正在使用.NET Framework 3.5,如何做到這一點呢? – 2011-05-17 12:53:35

+0

+1有趣的是,我在IE中的silverlight應用會得到json,而在firefox 4中運行的同一個應用會得到xml。這固定它。 – 2011-06-07 15:13:37

+25

+1令人難以置信的ResponseFormat = WebMessageFormat.Json如何被默默地忽略,你必須弄清楚這一點!如果沒有谷歌,WCF將完全無法使用 – Andomar 2011-07-25 11:30:30

5

對我來說,在WebGet屬性中將響應格式設置爲JSON不起作用。將其設置在方法的主體中;

// This works 
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; 
return jsonData; 


// This doesn't work 
`[WebGet(UriTemplate = "/conditions?term={term}", ResponseFormat = WebMessageFormat.Json)]` 
6
<system.serviceModel> 
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> 
     <standardEndpoints> 
      <webHttpEndpoint> 
       <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/> 
      </webHttpEndpoint> 
     </standardEndpoints> 
</system.serviceModel> 

更改兩個屬性在web.config中會解決這個問題:

  • automaticFormatSelectionEnabled=false
  • defaultOutgoingResponseFormat=Json(編輯:從 「真」)