I've been attempting to utilize a data service function by making a jquery ajax call. Despite trying various methods of calling it and configuring the Service Contract and Data Service, I keep receiving XML as a response. Some have suggested using jsonp, but I'm not sure if that's really necessary.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Utilize a data contract as shown in the example below to include composite types in service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
This is my data service class
public class MyService : DataService<MyEntities>
{
private readonly MyEntities _dataSource;
public MyService() : this(new MyEntities()) { }
// Using DI for testing service operations with a local DB
public MyService(MyEntities dataSource)
{
_dataSource = dataSource;
}
protected override MyEntities CreateDataSource()
{
return _dataSource;
}
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Teams", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
And here is the jquery ajax being used. It currently alerts an error message, and upon inspecting the console errors, I found it to be a json parse error due to receiving XML.
var url = "http://localhost:2884/MyService.svc/Teams";
$.ajax({
type: "GET",
url: url,
contentType: 'application/json; charset=utf-8',
accept: 'application/json',
dataType: 'json',
success: function (msg) {
alert(msg.d);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("error : " + xhr + ajaxOptions + thrownError);
}
});