开发者

Make my WCF service return json

开发者 https://www.devze.com 2023-01-15 19:52 出处:网络
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.

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 (item开发者_Python百科s.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 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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消