WCF 4.0:WebMessageFormat.Json不使用WCF REST模板

Rya*_*yan 30 wcf

从下载的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" } };
    }
Run Code Online (Sandbox Code Playgroud)

请注意ResponseFormat = WebMessageFormat.Json.这是我对该模板所做的唯一改变.

我错过了什么?

谢谢!

Rya*_*yan 56

想通了.automaticFormatSelectionEnabled应将standardendpoint的属性设置为,false并将defaultOutgoingReponseFormat设置为Json.

<standardEndpoint name="" helpEnabled="true" 
    automaticFormatSelectionEnabled="false" 
    defaultOutgoingResponseFormat ="Json" />
Run Code Online (Sandbox Code Playgroud)

  • +1令人难以置信的如何`ResponseFormat = WebMessageFormat.Json`被默默地忽略,你必须弄清楚这一点!没有谷歌,WCF将完全无法使用 (25认同)
  • 在.NET 4.0中,我只需要设置automaticFormatSelectionEnabled ="false".该方法使用ResponseFormat = WebMessageFormat.Json标记,并且有效.无需设置defaultOutgoingResponseFormat (4认同)

小智 6

 <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        <standardEndpoints>
            <webHttpEndpoint>
                <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/>
            </webHttpEndpoint>
        </standardEndpoints>
 </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

对web.config中2个属性的更改将修复它:

  • automaticFormatSelectionEnabled=false
  • defaultOutgoingResponseFormat=Json (编辑:来自"真实")


Ali*_*r77 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)]`
Run Code Online (Sandbox Code Playgroud)