0

我正在尝试使用 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);
            }
});
4

1 回答 1

0

如果有人在 WCF 数据服务的这一点上卡住了,那么很容易假设您刚刚开始,就像我一样。

我对这个问题的解决方案是从 WCF 转移到 Web API(微软似乎也在做同样的事情)参考: http: //www.codeproject.com/Articles/341414/WCF-or-ASP-NET- Web-APIs-My-two-cents-on-the-subject

再加上看看事情有多简单,我能够在几分钟内让它工作。

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);
        });

是的,这好多了:DI 使用了本教程 http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

于 2013-04-06T17:21:20.243 回答