加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – Web API错误:’ObjectContent`1’类型无法序列

发布时间:2020-12-16 00:14:22 所属栏目:asp.Net 来源:网络整理
导读:我在尝试使用Web API控制器时收到此错误. Web API Error: The ‘ObjectContent`1’ type failed to serialize the response body for content type 我的控制器中的代码如下 public IEnumerableStudent GetAllStudents() { var allstudents = unitOfWork.Stud
我在尝试使用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 {...}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读