始终有错误“ObjectContent 1类型无法序列化响应正文...” [英] Always have error "The ObjectContent 1 type failed to serialize the response body..."

查看:2041
本文介绍了始终有错误“ObjectContent 1类型无法序列化响应正文...”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Web api to retrieve data from the database. I only have 1 table "tblMessage" and want to get data from that table.

我设置了所有的东西,但是当我运行网站。错误总是说

I set everything up but then when I run the website. the error always say


'ObjectContent`1'类型无法序列化内容类型'application / xml

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

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

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


'ObjectContent`1'类型无法将内容类型'application / json

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

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

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

Web API错误:'ObjectContent`1'类型无法将响应主体序列化为内容类型

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

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

这个错误是什么? / p>

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


推荐答案

更改 IEnumerable< Message > to 列表< Message>

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

to

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

更新:
但要注意获取 OutOfMemoryException 因为这个方法会将所有消息对象存储在本地内存中,所以你必须实现某种寻呼。

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.

这篇关于始终有错误“ObjectContent 1类型无法序列化响应正文...”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆