Always have error “The ObjectContent 1 type failed to serialize the response body…”

后端 未结 4 461
再見小時候
再見小時候 2021-01-02 11:03

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 th

相关标签:
4条回答
  • 2021-01-02 11:51

    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);
    
    0 讨论(0)
  • 2021-01-02 11:56

    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.

    0 讨论(0)
  • 2021-01-02 11:56

    For these kinds of data querying you should definitely create paging for results. You have 2 options for paging in Web API.

    The first option you could use OData to return IQueryable object from your action method. So that, your action supports paging.

    The second option is to create a controller which supports paging. I put one example below.

    [HttpGet]
    public List<Book> Books(int page = 0 , int size = 100){
    
        using(var context = new BooksDataContext()){
    
            List<Book> books = context.Books.OrderBy(t=> t.CreateDate).Skip(page * size).Take(size).ToList();
    
            return books;
        }
    
    }
    

    The code above supports paging and you are able to set collection count that is going to return from the client side.

    0 讨论(0)
  • 2021-01-02 12:01

    I had the same problem and this is the solution I found

    After updating the Entity Data Model you have to set ProxyCreationEnabled to false in your Model

    Configuration.ProxyCreationEnabled = false;

    My example:

    public partial class EventsEntities : DbContext
    {
            public EventsEntities()
                : base("name=EventsEntities")
            {
                Configuration.ProxyCreationEnabled = false;
            }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                throw new UnintentionalCodeFirstException();
            }
    }
    
    0 讨论(0)
提交回复
热议问题