我试图通过jquery ajax调用消费数据服务函数,我试过很多方式调用它,并设置服务合同和数据服务,但没有重要的是它给我的XML。我听说有人说我需要使用jsonp,但这真的有必要吗?WCF数据服务没有响应与json,只有xml
[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
}
// Use a data contract as illustrated in the sample below to add composite types to 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; }
}
}
这是我的数据服务类
public class MyService : DataService<MyEntities>
{
private readonly MyEntities _dataSource;
public MyService() : this(new MyEntities()) { }
// im doing DI since I am testing my 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;
}
}
,这是jQuery的阿贾克斯。它只会提醒错误,当我检查控制台中的错误时,它会因为获取XML而导致json解析错误。
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);
}
});
您是否尝试过改变accept头?大多数OData服务将使用这些来确定要回放的内容类型。 – Rich 2013-04-05 03:58:35
我做了,默认情况下它的设置为JSON,仍然剂量工作:/我贴现在它现在接受:应用程序/ JSON,文本/ JavaScript,*/*; q = 0.01 – 2013-04-05 05:00:07
你应该保持终点的json响应 – 2013-04-05 05:36:46