Error while deserializing the object in WCF

2020-02-02 01:26发布

问题:

I have created a REST Service in WCF. I am facing the following issue

There was an error deserializing the object of type System.Collections.Generic.IList. The maximum read depth (32) has been exceeded because XML data being read has more levels of nesting than is allowed by the quota. This quota may be increased by changing the MaxDepth property on the XmlDictionaryReaderQuotas object used when creating the XML reader.

I haven't specified any type of binding in configuration since I have developed the service as per REST Starter Kit. Please suggest something as to how can I fix it.

The code is working fine sometimes but it do throw error.

回答1:

In my case, the problem was that I was returning Entity Framework objects that I got from the data context. The solution was to detach each object before retuning them.



回答2:

In my case, detaching objects was not possible because the EF context was already disposed.

Instead, I used the AsNotTracking extension method.

...On some other cases, I also had to cut circular references by setting some navigation properties to null.

...And DataContract(IsReference = true) did not do the trick.

More details on this issue can be found here : N-tier Entity Framework and debugging WCF problems



回答3:

REST Starter Kit is no longer supported and ASP.NET Web API or any other up-to-date REST framework should be used instead.



回答4:

I had the same issue today. It could be a circular reference if you don't have set correctly the KnowType and the IsReference in your data contract. Check those points first. Really !

But when your are facing this kind of behavior.

The code is working fine sometimes but it do throw error.

You should also check if the graph your are sending on the wire is deep and complex (like more than two navigation properties deep). Then it could just be the MaxDepth of the ReaderQuotas in your binding configuration which is too low. Your service would work when your deepest navigations properties are empty but would throw this error when they contains at least one element.

Default value of this configuration is 32, so give a try to 64.

Now we can argue about the poor quality design of using too much deep graph on service versus the low default value in WCF Configuration.

I'm not saying you have to break your graph in smaller part, but you should.