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;
}
}
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.
WCF supports serializing data in JSON format.
Have you tried:
[WebGet(ResponseFormat= WebMessageFormat.Json)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With