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:47

I don't like this code:

foreach(var user in db.Users)

As an alternative, one might do something like this, which worked for me:

var listOfUsers = db.Users.Select(r => new UserModel
                         {
                             userModel.FirstName = r.FirstName;
                             userModel.LastName = r.LastName;

                         });

return listOfUsers.ToList();

However, I ended up using Lucas Roselli's solution.

Update: Simplified by returning an anonymous object:

var listOfUsers = db.Users.Select(r => new 
                         {
                             FirstName = r.FirstName;
                             LastName = r.LastName;
                         });

return listOfUsers.ToList();
查看更多
牵手、夕阳
3楼-- · 2019-01-02 20:47

My personal favorite: Just add the code below to App_Start/WebApiConfig.cs. This will return json instead of XML by default and also prevent the error you had. No need to edit Global.asax to remove XmlFormatter etc.

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

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
查看更多
何处买醉
4楼-- · 2019-01-02 20:47

Another case where I received this error was when my database query returned a null value but my user/view model type was set as non-nullable. For example, changing my UserModel field from int to int? resolved.

查看更多
残风、尘缘若梦
5楼-- · 2019-01-02 20:51

If you are working with EF, besides adding the code below on Global.asax

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);          

Dont`t forget to import

using System.Data.Entity;

Then you can return your own EF Models

Simple as that!

查看更多
泪湿衣
6楼-- · 2019-01-02 20:53

This also happens when the Response-Type is not public! I returned an internal class as I used Visual Studio to generate me the type.

internal class --> public class
查看更多
长期被迫恋爱
7楼-- · 2019-01-02 20:54

Add this code to global.asax below on Application_Start:

Update from .Ignore to .Serialize . It must work.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
查看更多
登录 后发表回答