我正在尝试使用jquery ajax调用来使用数据服务函数,我尝试了很多方法来调用它,并设置了服务契约和数据服务,但不管它一直给我XML。我听说有人说我需要使用jsonp,但这真的有必要吗?
[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 ajax。它只警告错误,当我检查控制台中的错误时,它的json解析错误,因为它获取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);
}
});
答案 0 :(得分:0)
如果有人在WCF数据服务中遇到困难,那么很容易假设您刚刚开始,就像我一样。
我解决这个问题的方法是从WCF转移到Web API(微软似乎也在这样做)参考:http://www.codeproject.com/Articles/341414/WCF-or-ASP-NET-Web-APIs-My-two-cents-on-the-subjec
再看看有多简单,我能在几分钟内完成它。
public class TeamsController : ApiController
{
Team[] teams; // defined by whatever persistant means u want. ie. Entity Framework.
public IEnumerable<Team> GetAllTeams()
{
return teams;
}
}
然后我的JS
$.getJSON("api/teams/",
function (data) {
alert(data);
});
是的,这要好得多:D我用过这个教程 http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api