I just created my first WCF REST service. I wanted it to return JSON, so i especified the response format. At first, I was frustrated because it was returning SOAP all the time and I didn't know why, but I saw that a blogger was using Fiddler, so I tried with it and then I got a JSON response.
I think that the reason is because Fiddler is not sending this HTTP header:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
But then I tried to craft a request using this header:
Accept: application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
But it didn't work. How is WCF deciding when to use JSON or SOAP?
Is there a way to force to return JSON always?
I would like to be sure that when I consume the service, it will return JSON and not SOAP.
Thanks.
Update: Sample code:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json, RequestFormat= 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" } };
}
[WebInvoke(UriTemplate = "", Method = "POST")]
public SampleItem Create(SampleItem instance)
{
// TODO: Add the new instance of SampleItem to the collection
throw new NotImplementedException();
}
[WebGet(UriTemplate = "{id}", ResponseFormat = WebMessageFormat.Json)]
public SampleItem Get(string id)
{
// TODO: Return the instance of SampleItem with the given id
return new SampleItem() { Id = Int32.Parse(id), StringValue = "Hello" };
}
}