9

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;
    }
}
Toji
  • 33,927
  • 22
  • 105
  • 115
Zinoo
  • 185
  • 2
  • 3
  • 7

2 Answers2

7

Have you tried:

[WebGet(ResponseFormat= WebMessageFormat.Json)]
tomasr
  • 13,683
  • 3
  • 38
  • 30
  • thanks. Yes i tried but i still get error from the JQuery code. here is the code i am using to call the service: var parameters = 7 $.ajax({ type: "POST", url: "http://localhost:53153/TestWebServiceEightSite/CostService.svc", data: parameters, contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { $("InputHTML").val(result); }, error: function(e) { alert(e); } }); – Zinoo Dec 02 '09 at 03:48
1

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.

Oliver
  • 9,239
  • 9
  • 69
  • 100