我在尝试使用Web API控制器时收到此错误.
Web API Error: The ‘ObjectContent`1’ type Failed to serialize the response body for content type
我的控制器中的代码如下
public IEnumerable<Student> GetAllStudents() { var allstudents = unitOfWork.StudentRepository.Get(includeProperties: "Groups"); return allstudents; } public Student GetStudentByID(Guid id) { return unitOfWork.StudentRepository.GetByID(id); }
我的’学生’课程如下
public partial class Student { public Student() { this.Groups = new HashSet<Group>(); } public System.Guid StudentID { get; set; } public string Surname { get; set; } public string FirstName { get; set; } public byte[] Timestamp { get; set; } public virtual Course Course { get; set; } public virtual ICollection<Group> Groups { get; set; } }
我内心的例外情况如下
Type
‘System.Data.Entity.DynamicProxies.Student_4C97D068E1AD0BA62C3C6E441601FFB7418AD2D635F7F1C14B64F4B2BE32DF9A’
with data contract name
‘Student_4C97D068E1AD0BA62C3C6E441601FFB7418AD2D635F7F1C14B64F4B2BE32DF9A:07000’
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types – for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
我有一种感觉,我需要使用KnownType属性,但我不确定如何实现它.
任何帮助,将不胜感激
解决方法
什么是内部异常消息?内部异常消息将是序列化程序抛出的实际异常,它应该告诉我们哪种类型导致异常.
让我猜一下 – 它是类型课程和类型组吗?如果是这样,请尝试将KnownType属性放在类Student的实际实现类型上
[KnownType(typeof(GroupA))] [KnownType(typeof(CourseA))] public partial class Student {...} public class GroupA : Group {...} public class CourseA : Course {...} public interface Group {...} public interface Course {...}