Wcf Shopify与Newtonsoft(JSON.NET)问题

Wcf Shopify与Newtonsoft(JSON.NET)问题,wcf,json.net,shopify,Wcf,Json.net,Shopify,我在构建WCF服务时遇到了一个无法解决的问题,我在哪里遇到了错误: “类型'Newtonsoft.Json.Linq.JToken'是一个递归数据集合 不支持的合同。请考虑修改定义。 集合“Newtonsoft.Json.Linq.JToken”以删除对的引用 本身” 我知道主要的解决方案是取消选中在我的服务引用中重用Newtonsoft引用的选项,但我没有列出要取消选中的选项。我确认json.net在我的服务中被正确引用 奇怪的是,当我离开这个电话时,我确认我得到了结果 public List

我在构建WCF服务时遇到了一个无法解决的问题,我在哪里遇到了错误:

“类型'Newtonsoft.Json.Linq.JToken'是一个递归数据集合 不支持的合同。请考虑修改定义。 集合“Newtonsoft.Json.Linq.JToken”以删除对的引用 本身”

我知道主要的解决方案是取消选中在我的服务引用中重用Newtonsoft引用的选项,但我没有列出要取消选中的选项。我确认json.net在我的服务中被正确引用

奇怪的是,当我离开这个电话时,我确认我得到了结果

public List<T> CallService<T>(string query)
    {

        var data = new List<T>();
        var fullyEscapedUri = _ShopUri.AbsoluteUri.EndsWith("/") ? _ShopUri : new Uri(_ShopUri + "/");
        var uri = new Uri(fullyEscapedUri, typeof(T).Name);

        if (!string.IsNullOrWhiteSpace(query))
        {

            var uriBuilder = new UriBuilder(uri) { Query = query };
            uri = uriBuilder.Uri;

        }

        string url = String.Format("{0}{1}", _ShopUri, query);
        var request = WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/json";

        string base64EncodedUsernameAndPassword = string.Format("{0}:{1}", _Username, _Password);
        string authHeader = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(base64EncodedUsernameAndPassword)));
        request.Headers["Authorization"] = authHeader;

        using (var response = request.GetResponse())
        {

            using (var stream = response.GetResponseStream())
            {

                using (var reader = new StreamReader(stream))
                {

                    string json = reader.ReadToEnd();
                    var jsonObj = JsonConvert.DeserializeObject(json, new JsonSerializerSettings()
                    {
                        Formatting = Formatting.Indented,
                        TypeNameHandling = TypeNameHandling.Auto,
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        NullValueHandling = NullValueHandling.Ignore,
                        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

                    }) as JObject;
                    var jsonArray = jsonObj[_ObjectType] as JArray;

                    foreach (var jsonEmp in jsonArray)
                    {

                        var obj = JsonConvert.DeserializeObject<T>(jsonEmp.ToString());
                        data.Add(obj);


                    }

                }

            }

        }

        return data;
    }
strong文本

我已经在我的客户端应用程序中搜索了对Newtonsoft的所有引用,但我没有找到任何或任何线索表明它被“递归地”调用。我已经删除并重新添加了服务引用,同样的问题

服务和客户端都是v4.6.1

有什么想法吗

编辑:由于某些原因,我现在无法触发错误,但当它发生时,我将此作为外部异常,然后是带有内部异常的主要错误消息:

 Unhandled Exception: System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost:3000/OrderService.svc/GetOrders. This could be due to the service endpoint 
binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). 
See server logs for more details. 
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. 
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. 
---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at ShopifyServiceClient.OrderService.IOrderService.GetOrders(String query)
   at ShopifyServiceClient.OrderService.OrderServiceClient.GetOrders(String query)
   at ShopifyServiceClient.Program.Main(String[] args)

在内心深处

System.Runtime.Serialization.InvalidDataContractException, System.Runtime.Serialization,版本=4.0.0.0,区域性=中性, PublicKeyToken=b77a5c561934e089

类型“Newtonsoft.Json.Linq.JToken”是一个递归数据集合 不受支持的合同。考虑修改定义 集合“Newtonsoft.Json.Linq.JToken”以删除对的引用 本身

以下是我的服务的入口点:

public class OrderService : IOrderService
{

    public ReturnContract GetOffset()
    {
        return new ReturnContract { Offset = new DateTimeOffset(DateTime.Now) };
    }

    //non-async calls
    public List<Order> GetOrders(string query)
    {

        OrderData orders = new OrderData(query);
        return orders.CallOrders();

    }

    [DataContract]
    [KnownType(typeof(DateTimeOffset))]
    public class ReturnContract
    {
        [DataMember]
        public DateTimeOffset? Offset { get; set; }
    }


    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

在这种情况下,这是一个JSON反序列化问题。过去发生这种情况时,我收到了“对象引用未设置为对象实例”错误。我觉得这很奇怪,因为我确实看到Shopify对象从服务中返回

您是否可以将您的问题分享给我们,分享异常的完整输出,包括异常类型、消息、回溯和内部异常(如果有)?另外,您在哪里调用
CallService
,传入的是什么类型的
T
?你能和我分享一个吗?这太奇怪了。我只是运行了我的应用程序来获取要发布的堆栈跟踪,它工作得很好。需要注意的一件事是,几天前,在我克服了一些其他错误后,我确实成功地让它工作了,但几小时后,我再次测试了它,它停止了工作。我想可能是API端点发生了节流,或者是我们的开发服务器在内部阻止了什么。我仍将按照您的要求,使用堆栈跟踪和一些其他代码编辑我的注释。谢谢你的回复!也许你会看到或者。错误消息类型“Newtonsoft.Json.Linq.JToken”是一个不受支持的递归收集数据协定,当尝试使用
DataContractJsonSerializer
而不是Newtonsoft为
JToken
序列化或生成数据协定时,将生成该协定。我认为这肯定是服务器问题,因为它现在正在发生零星我已经从我们的基础设施团队寻求帮助,帮助解决问题。一旦我们得到更多线索,我会发布一个决议。
 Unhandled Exception: System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost:3000/OrderService.svc/GetOrders. This could be due to the service endpoint 
binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). 
See server logs for more details. 
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. 
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. 
---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at ShopifyServiceClient.OrderService.IOrderService.GetOrders(String query)
   at ShopifyServiceClient.OrderService.OrderServiceClient.GetOrders(String query)
   at ShopifyServiceClient.Program.Main(String[] args)
public class OrderService : IOrderService
{

    public ReturnContract GetOffset()
    {
        return new ReturnContract { Offset = new DateTimeOffset(DateTime.Now) };
    }

    //non-async calls
    public List<Order> GetOrders(string query)
    {

        OrderData orders = new OrderData(query);
        return orders.CallOrders();

    }

    [DataContract]
    [KnownType(typeof(DateTimeOffset))]
    public class ReturnContract
    {
        [DataMember]
        public DateTimeOffset? Offset { get; set; }
    }


    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}
internal class OrderData
{
    private string _shopifyStore = Global.EcomShop;
    private string _apiKey = Global.EcomShopAPIKey;
    private string _apiPassword = Global.EcomShopAPIPassword;       
    private string _query;

    internal OrderData(string query)
    {
        _query = query;
    }



    internal List<Order> CallOrders()
    {
        var orderService = new ShopifyService(_shopifyStore, _apiKey, _apiPassword, "orders");
        var orders = orderService.CallService<Order>(_query);
        return orders;            

    }

}