【问题标题】:Always have error "The ObjectContent 1 type failed to serialize the response body..."总是出现错误“ObjectContent 1 类型无法序列化响应正文...”
【发布时间】:2013-08-10 15:39:50
【问题描述】:

我使用 Web api 从数据库中检索数据。我只有 1 个表“tblMessage”并想从该表中获取数据。

我设置了所有内容,但是当我运行网站时。错误总是说

“ObjectContent`1”类型无法序列化内容类型“application/xml”的响应正文

我在 stackoverflow 上阅读了一些帖子,上面说可以通过告诉浏览器以 json 格式输出数据来修复错误。之后,错误变为

“ObjectContent`1”类型无法序列化内容类型“application/json”的响应正文

我已经尝试了以下帖子中的所有解决方案,但它们没有解决问题(浏览器报告相同的错误)

Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type

Failed to serialize the response body for content type

Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type

这个错误到底是什么?

public interface IMessage
{
    IQueryable<Message> GetAll();
}

public class Message
{
    [Key]
    public int i_StmID { get; set; }
    public string vch_MsgString { get; set; } 
}

public class EFDBContext : DbContext
{
    public DbSet<Message> Message { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Message>().ToTable("tblMessage");
    }
}

public class MessageRepository : IMessage
{
    private EFDBContext context = new EFDBContext();

    public IQueryable<Message> GetAll()
    {
        return context.tblMessage;
    }
}

public class MessageController : ApiController
{
    public IMessage repo = new MessageRepository();

    public IEnumerable<Message> GetAllMsg()
    {
        return repo.GetAll();
    }
}

【问题讨论】:

    标签: c# entity-framework serialization asp.net-web-api json.net


    【解决方案1】:

    IEnumerable&lt;Message> 更改为List&lt;Message&gt;

    public IEnumerable<Message> GetAllMsg()
    {
        return repo.GetAll();
    }
    

    public List<Message> GetAllMsg()
    {
        return repo.GetAll();
    }
    

    更新: 但要小心获取OutOfMemoryException,因为此方法会将所有Message 对象存储在本地内存中,因此您必须实现某种分页。

    【讨论】:

    • 谢谢。我阅读了有关此问题的帖子并添加了相同的内容,但浏览器报告了相同的错误。我认为错误是由代码产生的
    • 再次感谢。不幸的是,我的代码没有编译 b/c context.tblMessage 返回一个 DbSet,而不是 List。我试过“return context.tblMessage.ToList()”但失败了。
    • 其实现在已经编译好了。但它会抛出 OutOfMemoryException。我该如何解决这个问题?
    • @kaboom 实际上是的,它会抛出 OutOfMemExcep,因为您试图将所有消息存储在内存中,您应该使用 GetAllMsg().Skip(page-1*pageSize) 实现某种分页示例。取(pageSize)
    • 改用IQueryable&lt;T&gt;不好吗?
    【解决方案2】:

    我遇到了同样的问题,这是我找到的解决方案

    更新实体数据模型后,您必须在模型中将ProxyCreationEnabled 设置为false

    Configuration.ProxyCreationEnabled = false;

    我的例子:

    public partial class EventsEntities : DbContext
    {
            public EventsEntities()
                : base("name=EventsEntities")
            {
                Configuration.ProxyCreationEnabled = false;
            }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                throw new UnintentionalCodeFirstException();
            }
    }
    

    【讨论】:

      【解决方案3】:

      对于这些类型的数据查询,您绝对应该为结果创建分页。在 Web API 中,您有 2 个分页选项。

      您可以使用 OData 从您的操作方法返回 IQueryable 对象的第一个选项。因此,您的操作支持分页。

      第二个选项是创建一个支持分页的控制器。下面我举一个例子。

      [HttpGet]
      public List<Book> Books(int page = 0 , int size = 100){
      
          using(var context = new BooksDataContext()){
      
              List<Book> books = context.Books.OrderBy(t=> t.CreateDate).Skip(page * size).Take(size).ToList();
      
              return books;
          }
      
      }
      

      上面的代码支持分页,您可以设置将从客户端返回的集合计数。

      【讨论】:

        【解决方案4】:

        我在 Chrome 上遇到了同样的问题,而在 IE 上则没有这么多。为了修复它,我在 Global.asax.cs, Application_Start() 方法中使用了以下几行:

        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
        

        【讨论】:

          猜你喜欢
          • 2012-10-07
          • 2017-07-17
          • 1970-01-01
          • 2016-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-01
          相关资源
          最近更新 更多