Always have error "The ObjectContent 1 type failed to serialize the response body..."

asp.net-web-api c# entity-framework json.net serialization

Question

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

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

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

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 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();
    }
}
1
8
5/23/2017 10:31:13 AM

Accepted Answer

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.

5
8/8/2013 8:21:22 PM

Popular Answer

I had the same issue with Chrome, not so much with IE. In order to fix it I used the following lines at the Global.asax.cs, Application_Start() method:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow