Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Json from WCF Service?

Tags:

json

wcf

I have the piece of code below of a template Ajax enabled WCF service. What can i do to make it return JSon instead of XML? thanks.

using System; 
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

[ServiceContract(Namespace = "WCFServiceEight")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CostService
{
    // Add [WebGet] attribute to use HTTP GET
    [OperationContract]
    [WebGet]
    public double CostOfSandwiches(int quantity)
    {
        return 1.25 * quantity;
    }
}
like image 468
Zinoo Avatar asked Dec 02 '09 03:12

Zinoo


People also ask

Can we return JSON from WCF service?

WCF has option to send the response in JSON object. This can be configured with WebGet or WebInvoke attribute. In this sample we can create the sample RESTful service to expose the method to read/add/update/delete the employee information.

Does WCF support JSON?

WCF supports serializing data in JSON format.


2 Answers

Have you tried:

[WebGet(ResponseFormat= WebMessageFormat.Json)]
like image 56
tomasr Avatar answered Sep 21 '22 12:09

tomasr


If you want to use the POST verb as in $.ajax({ type: "POST", ...) you will need to markup your method with [WebInvoke(Method="POST"].

Since you marked it up with [WebGet] (which is equivalent to [WebInvoke(Method="GET")]) you should call the service using the GET verb, e.g.:

$.ajax({ type: "GET", ...) or use $.get(url, data, ...) (see jQuery.get for more info).

And you'll need to set the ResponseFormat to Json, as tomasr already pointed out.

like image 26
Oliver Avatar answered Sep 20 '22 12:09

Oliver