views:

86

answers:

2

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;  
}  
+1  A: 

In order for this to work, you need to host this with the webHttpBinding and the WebServiceHostFactory in your web.config and service's *.svc file.

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 WebGet attribute is only supported in the REST-style WCF services. The WebGet attribute is ignored for any of the SOAP-based bindings, e.g. basicHttpBinding, wsHttpBinding, netTcpBinding and 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 WebGet attribute and returns JSON, you need to make sure to specify the correct service host factory:

<%@ServiceHost Language="C#" Service="YourService"
               Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

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.

marc_s
the example that you gave me is, .cs-file
Troj
what are the differences of .svc-file and .csfile, working as services
Troj
@Troj: updated my answer with *.svc information
marc_s
A: 

Have you also set the WebHttpBehaviour ? Otherwise, WebGet does not work. See MSDN

And this attribute applies to Service operations, not simple methods. You do not show the rest of your services, but the examples I've seen using WebGet had this attribute in the interface (service contract).

Timores
Iam not using any indetface, iam using a -svc-file
Troj