本文介绍了总是有误差"该ObjectContent 1类型没有序列化响应主体..."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Web API从数据库中检索数据。我只有1台tblMessage,想从该表中获取数据。

我把一切都弄好但后来当我运行的网站。错误总是说

I read some posts on stackoverflow that sayid the error could be fixed by telling the browser to output data in json format. After that, the error becomes

I have tried all solutions from the following posts, but they dont fix the problem ( browser reports the same error)

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

What exactly this error is?

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();
    }
}
解决方案

Change IEnumerable<Message> to List<Message>

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

to

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

UPDATE:But beware of getting OutOfMemoryException because this method will store all Message objects in local memory so you have to implement some kind of paging.

这篇关于总是有误差&QUOT;该ObjectContent 1类型没有序列化响应主体...&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:45
查看更多