Failed to serialize the response in Web API with J

2019-01-02 19:48发布

I am working with ASP.NET MVC 5 Web Api. I want consult all my users.

I wrote api/users and I receive this:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

In WebApiConfig, already I added these lines:

HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

But it still doesn't work.

My function for return data is this:

public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}

18条回答
十年一品温如言
2楼-- · 2019-01-02 20:34

Use AutoMapper...

public IEnumerable<User> GetAll()
    {
        using (Database db = new Database())
        {
            var users = AutoMapper.Mapper.DynamicMap<List<User>>(db.Users);
            return users;
        }
    }
查看更多
美炸的是我
3楼-- · 2019-01-02 20:35

If you are working with EntityFramework, you should disable proxy in your DbContext class constructor as,

public class MyDbContext : DbContext
{
  public MyDbContext()
  {
    this.Configuration.ProxyCreationEnabled = false;
  }
}
查看更多
看淡一切
4楼-- · 2019-01-02 20:37

In my case I have had similar error message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

But when I dig deeper in it, the issue was:

Type 'name.SomeSubRootType' with data contract name 'SomeSubRootType://schemas.datacontract.org/2004/07/WhatEverService' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

The way I solved by adding KnownType.

[KnownType(typeof(SomeSubRootType))]
public partial class SomeRootStructureType

This was solved inspired from this answer.

Reference: https://msdn.microsoft.com/en-us/library/ms730167(v=vs.100).aspx

查看更多
路过你的时光
5楼-- · 2019-01-02 20:43

Use the following namespace:

using System.Web.OData;

Instead of :

using System.Web.Http.OData;

It worked for me

查看更多
妖精总统
6楼-- · 2019-01-02 20:46

Solution that worked for me:

  1. Use [DataContract] for class and [DataMember] attributes for each property to serialize.This is enough to get Json result (for ex. from fiddler).

  2. To get xml serialization write in Global.asax this code:

    var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true;

  3. Read this article, it helped me to understand serialization: https://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization
查看更多
琉璃瓶的回忆
7楼-- · 2019-01-02 20:47

Given right answer is one way to go, however it is an overkill when you can fix it by one config settings.

Better to use it in the dbcontext constructor

public DbContext() // dbcontext constructor
            : base("name=ConnectionStringNameFromWebConfig")
{
     this.Configuration.LazyLoadingEnabled = false;
     this.Configuration.ProxyCreationEnabled = false;
}

Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'

查看更多
登录 后发表回答