Reputation: 861
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!
Upvotes: 30
Views: 19223
Reputation: 29181
I was hitting issues like this every time I tried to create a JSON web service.
Now, I just follow the steps shown here.
It shows how to create a JSON web service, step-by-step, with screenshots and examples.
Hope this helps.
Upvotes: 0
Reputation: 61
<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")Upvotes: 6
Reputation: 861
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" />
Upvotes: 56
Reputation: 121
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
Upvotes: 1
Reputation: 1218
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)]`
Upvotes: 5