Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF 4.0 : WebMessageFormat.Json not working with WCF REST Template

Tags:

wcf

Downloaded the WCF REST Template from this location.

The default response format is XML, which works great. However, when I try to get a JSON response, I still get XML.

This is my modified code -

[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" } };
    }

Note the ResponseFormat=WebMessageFormat.Json. That is the only change I did to that template.

What am I missing?

Thanks!

like image 690
Ryan Avatar asked Sep 23 '10 18:09

Ryan


4 Answers

Figured out. automaticFormatSelectionEnabled property for standardendpoint should be set to false and defaultOutgoingReponseFormat should be set to Json.

<standardEndpoint name="" helpEnabled="true" 
    automaticFormatSelectionEnabled="false" 
    defaultOutgoingResponseFormat ="Json" />
like image 198
Ryan Avatar answered Oct 20 '22 12:10

Ryan


 <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        <standardEndpoints>
            <webHttpEndpoint>
                <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/>
            </webHttpEndpoint>
        </standardEndpoints>
 </system.serviceModel>

Changes to 2 attributes within the web.config will fix it:

  • automaticFormatSelectionEnabled=false
  • defaultOutgoingResponseFormat=Json (edited: from "true")
like image 29
Ton Snoei Avatar answered Oct 20 '22 11:10

Ton Snoei


For me, setting the response format to JSON in the WebGet attribute doesn't work. Setting it in the body of the method does;

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


// This doesn't work
`[WebGet(UriTemplate = "/conditions?term={term}", ResponseFormat = WebMessageFormat.Json)]`
like image 5
Alistair77 Avatar answered Oct 20 '22 12:10

Alistair77


Click -> reference links

"When automatic format selection is enabled, the infrastructure parses the Accept header of the request message and determines the most appropriate response format. If the Accept header does not specify a suitable response format, the infrastructure uses the Content-Type of the request message or the default response format of the operation."

EDIT: this link might get you moving ahead http://blogs.msdn.com/b/endpoint/archive/2010/11/01/wcf-webhttp-service-returns-http-415-unsupported-media-type.aspx

like image 1
ChristoD Avatar answered Oct 20 '22 10:10

ChristoD