总是有错误”;ObjectContent 1类型未能序列化响应正文&”;

本文关键字:序列化 响应 正文 有错误 ObjectContent 类型 | 更新日期: 2023-09-27 18:26:52

我使用Web api从数据库中检索数据。我只有一个表"tblMessage",希望从该表中获取数据。

我设置了一切,但当我运行网站时。错误总是说

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

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

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

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

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

无法序列化内容类型的响应正文

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

这个错误到底是什么?

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

总是有错误”;ObjectContent 1类型未能序列化响应正文&”;

IEnumerable<Message>更改为List<Message>

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

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

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

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

更新实体数据模型后,您必须在模型中将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();
        }
}

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

第一个选项可以使用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;
    }
}

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

我在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);