gpt4 book ai didi

c# - 总是有错误 "The ObjectContent 1 type failed to serialize the response body..."

转载 作者:太空狗 更新时间:2023-10-29 18:27:08 25 4
gpt4 key购买 nike

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

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

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml

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

The 'ObjectContent`1' type failed to serialize the response body for content type '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();
}
}

最佳答案

更改 IEnumerable<Message > 至 List<Message>

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

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

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

关于c# - 总是有错误 "The ObjectContent 1 type failed to serialize the response body...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18134271/

25 4 0