"Type not expected", using DataContractSerializer - but it's just a simple class, no funny stuff?
The exception that is being reported is for VDB_Sync.Model.Konstant. This means that somewhere further up the chain, this class is being pulled into another class and that class is the one being serialized.
The issue is that depending on how Konstant is embedded in this class (for example, if it is in a collection or a generic list), the DataContractSerializer may not be prepared for its appearance during deserialization.
To resolve this, you need to apply the known-type attribute to the class that contains Konstant. Based on your serialization code, I suspect that this is VDB_SessionController
.
So, try decorating this class with the KnownType attribute:
[KnownType(typeof(VDB_Sync.Model.Konstant)]
public class VDB_SessionController
Add this to WebApiConfig.cs
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
Reference: http://www.datazx.cn/Forums/en-US/a5adf07b-e622-4a12-872d-40c753417645/action?threadDisplayName=web-api-error-the-objectcontent1-type-failed-to-serialize-the-response-body-for-content&forum=wcf
You can also combine [KnownType]
and reflection to make your code more resistant to future changes.
[DataContract]
[KnownType("GetKnownPersonTypes")]
internal class Person
{
private static IEnumerable<Type> _personTypes;
private static IEnumerable<Type> GetKnownTypes()
{
if (_personTypes == null)
_personTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof (Person).IsAssignableFrom(t))
.ToList();
return _personTypes;
}
}
Now a DataContractSerializer
/ DataContractJsonSerializer
/ XmlSerializer
configured to work with Person
, will also work with any type derived from Person
(as long as it's declared within the same assembly).