始终有错误“ObjectContent 1类型无法序列化响应正文…”
我使用Web api从数据库中检索数据。 我只有一个表“tblMessage”,并希望从该表中获取数据。
我设置了所有内容但是当我运行网站时。 错误总是说
‘ObjectContent`1’类型无法序列化内容类型’application / xml的响应主体
我在stackoverflow上读了一些post,说明错误可以通过告诉浏览器以json格式输出数据来修复。 之后,错误就变成了
‘ObjectContent`1’类型无法序列化内容类型’application / json的响应主体
我已尝试过以下post中的所有解决方案,但他们没有解决问题(浏览器报告相同的错误)
Web API错误:’ObjectContent`1’类型无法序列化内容类型的响应正文
无法序列化内容类型的响应正文
Web API错误:’ObjectContent`1’类型无法序列化内容类型的响应正文
这个错误究竟是什么?
public interface IMessage { IQueryable GetAll(); } public class Message { [Key] public int i_StmID { get; set; } public string vch_MsgString { get; set; } } public class EFDBContext : DbContext { public DbSet Message { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity().ToTable("tblMessage"); } } public class MessageRepository : IMessage { private EFDBContext context = new EFDBContext(); public IQueryable GetAll() { return context.tblMessage; } } public class MessageController : ApiController { public IMessage repo = new MessageRepository(); public IEnumerable GetAllMsg() { return repo.GetAll(); } }
将IEnumerable
List
public IEnumerable GetAllMsg() { return repo.GetAll(); }
至
public List GetAllMsg() { return repo.GetAll(); }
更新:但要注意获取OutOfMemoryException
因为此方法将所有Message
对象存储在本地内存中,因此您必须实现某种类型的分页。
对于这些类型的数据查询,您肯定应该为结果创建分页。 在Web API中有2个分页选项。
您可以使用OData从操作方法返回IQueryable对象的第一个选项。 这样,您的操作支持分页。
第二个选项是创建一个支持分页的控制器。 我在下面举了一个例子。
[HttpGet] public List Books(int page = 0 , int size = 100){ using(var context = new BooksDataContext()){ List 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);
我有同样的问题,这是我找到的解决方案
更新实体数据模型后,您必须在模型中将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(); } }