我試圖通過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