2010-09-23 47 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(编辑:从 “真”)