I am trying to make my WCF service method to return JSON-object, but it doesn’t work, when I open in a web browser it shows xml.
How can I make this method return JSON?
I have inserted [WebGet(ResponseFormat = WebMessageFormat.Json)], but that didn’t help
[WebGet(ResponseFormat = WebMessageFormat.Json)]
protected override IEnumerable<KeyValuePair<string, SampleItem>> OnGetItems()
{
// TODO: Change the sample implementation here
if (items.Count == 0)
{
items.Add("A", new SampleItem() { Value = "A" });
items.Add("B", new SampleItem() { Value = "B" });
items.Add("C", new SampleItem() { Value = "C" });
}
return this.items;
}
In order for this to work, you need to host this with the
webHttpBindingand theWebServiceHostFactoryin your web.config and service’s*.svcfile.You didn’t show any web.config or other config – so I cannot really tell what you’re doing. But the JSON response format in the
WebGetattribute is only supported in the REST-style WCF services. TheWebGetattribute is ignored for any of the SOAP-based bindings, e.g.basicHttpBinding,wsHttpBinding,netTcpBindingand so on.For more information on REST-style WCF Services, check out the WCF REST Developer Center and read up on how to set up and use REST-style WCF services.
Update: in order for your *.svc file to properly work as a REST service that uses the
WebGetattribute and returns JSON, you need to make sure to specify the correct service host factory:By specifying the
WebServiceHostFactory, you’re telling the WCF runtime to use this service as a REST service, and then all the other pieces should automatically fall into place.