【问题标题】:Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content typeWeb API 错误:“ObjectContent`1”类型无法序列化内容类型的响应正文
【发布时间】:2012-10-07 20:27:24
【问题描述】:

我在尝试使用 Web API 控制器时收到此错误。

Web API 错误:“ObjectContent`1”类型无法序列化内容类型的响应正文

我的控制器中的代码如下

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; }
}

这两种方法都会导致相同的错误。

我内心的异常如下

类型 'System.Data.Entity.DynamicProxies.Student_4C97D068E1AD0BA62C3C6E441601FFB7418AD2D635F7F1C14B64F4B2BE32DF9A' 带有数据合同名称 '学生_4C97D068E1AD0BA62C3C6E441601FFB7418AD2D635F7F1C14B64F4B2BE32DF9A:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' 预计不会。考虑使用 DataContractResolver 或添加任何 已知类型列表中静态未知的类型 - 例如, 通过使用 KnownTypeAttribute 属性或将它们添加到 传递给 DataContractSerializer 的已知类型列表。

我觉得我需要使用KnownType 属性,但我不确定如何实现它。

任何帮助将不胜感激

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    什么是内部异常消息?内部异常消息将是序列化程序抛出的实际异常,它应该告诉我们是哪种类型导致了异常。

    让我猜猜——是Course 类型和Group 类型吗?如果是这样,请尝试将KnownType 属性放在class 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 {...}
    

    【讨论】:

    • 嗨,玛吉,感谢您的回复。我在上面添加了内部异常。
    • 我认为这不能回答问题。 @jjc99 -- 你为什么把它标记为已回答?问题在于继承自Student的类型是Entity Framework在运行时作为动态代理对象创建的,因此无法为其使用编译时的KnownType属性。
    • @Paul,你可能是对的。我所知道的是KnownTypeAttribute 设置了Inherited=true 选项。这意味着如果GroupAStudent 的实际实现分别继承自GroupAStudent(因此可以进行强制转换),并且序列化程序在内部使用Type.GetCustomAttributes(typeof(KnownTypeAttribute), true),这将起作用。尽管如此,我并不熟悉这些内部细节来绝对支持我的话,我只是认为即使具体类型是动态生成的也是可能的。
    【解决方案2】:

    如果您不需要代理类 (System.Data.Entity.DynamicProxies.Student_4C97D068E1A...) 提供的延迟加载导航属性,您可以通过设置禁用它们的生成:

    unitOfWork.Configuration.ProxyCreationEnabled = false;
    

    如果需要代理类怎么办是another question


    点击这些链接可以很好地了解延迟加载和代理:

    我通常默认禁用延迟加载和代理,并在需要它们的特定代码块中启用其中之一或两者。

    【讨论】:

    • 如果他仍然需要导航属性,可以将它们包含在return allStudents.Include( i =&gt; i.Groups)
    猜你喜欢
    • 2017-07-17
    • 1970-01-01
    • 2016-09-15
    • 2012-12-07
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多