Failed to serialize response in Web API using Json

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

I wrote api/users and get this:

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

In WebApiConfig, I already added these lines:

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

But that still doesn't work.

My function to return data is as follows:

 public IEnumerable<User> GetAll() { using (Database db = new Database()) { return db.Users.ToList(); } } 
+100
json c # asp.net-web-api
Apr 16 '14 at 2:56
source share
25 answers

When it comes to returning data to the user from Web Api (or any other web service), I highly recommend not transferring objects that come from the database. It is much more reliable and easy to use models in which you control how the data looks, not the database. That way, you don’t have to bother with formatter so much in WebApiConfig. You can simply create a UserModel with child models as properties and get rid of the reference loops in the returned objects. This makes the serializer much happier.

In addition, there is no need to remove formats or supported media types, as a rule, if you simply specify the “Accepts” header in the request. Playing with this material can sometimes be confusing.

Example:

 public class UserModel { public string Name {get;set;} public string Age {get;set;} // Other properties here that do not reference another UserModel class. } 
+71
Apr 16 '14 at 3:12
source share

If you work 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); 

Do not forget to import

 using System.Data.Entity; 

Then you can return your own EF models

Just like that!

+131
Mar 01 '15 at 1:08
source share

The correct answer is one way to go, however it can be excessive if you can fix it with a single configuration setting.

Better use it in dbcontext constructor

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

Asp.Net API error: ObjectContent`1 type could not serialize the response body for the content type 'application / xml; encoding = UTF-8 '

+52
Jul 04 '15 at 13:40
source share

Add this code to global.asax below on Application_Start :

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

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize; GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 
+33
Jan 14 '16 at 18:48
source share

I do not like this code:

foreach(var user in db.Users)

Alternatively, one could do something like this that worked for me:

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

However, I decided to use the Lucas Roselli solution.

Update: simplified by returning an anonymous object:

 var listOfUsers = db.Users.Select(r => new { FirstName = r.FirstName; LastName = r.LastName; }); return listOfUsers.ToList(); 
+10
Apr 09 '15 at 13:40
source share
 public class UserController : ApiController { Database db = new Database(); // construction public UserController() { // Add the following code // problem will be solved db.Configuration.ProxyCreationEnabled = false; } public IEnumerable<User> GetAll() { return db.Users.ToList(); } } 
+10
Sep 16 '16 at 14:21
source share

I decided using this code in the file WebApiConfig.cs

 var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter); 
+8
Mar 23 '18 at 13:28
source share

Also this script generates the same error:

In the case where return is a List<dynamic> for the web api method

Example:

 public HttpResponseMessage Get() { var item = new List<dynamic> { new TestClass { Name = "Ale", Age = 30 } }; return Request.CreateResponse(HttpStatusCode.OK, item); } public class TestClass { public string Name { get; set; } public int Age { get; set; } } 

So, for this scenario, use [KnownTypeAttribute] in the returned class (all of them) as follows:

 [KnownTypeAttribute(typeof(TestClass))] public class TestClass { public string Name { get; set; } public int Age { get; set; } } 

It works for me!

+6
Oct 24 '14 at 17:20
source share

Adding this to your Application_Start() method of the Global.asax file should fix the problem

 protected void Application_Start() { GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; GlobalConfiguration.Configuration.Formatters .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); // ... } 

METHOD 2: [Not recommended]
If you work with EntityFramework, you can disable proxies in your constructor of the DbContext class. NOTE: this code will be deleted if you update the model.

 public class MyDbContext : DbContext { public MyDbContext() { this.Configuration.ProxyCreationEnabled = false; } } 
+6
Jan 12 '18 at 4:31
source share

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

The type "ObjectContent`1" could not serialize the response body for the content type "application / xml"; encoding = UTF-8

 config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 
+4
Aug 12 '16 at 11:24
source share

Use AutoMapper ...

 public IEnumerable<User> GetAll() { using (Database db = new Database()) { var users = AutoMapper.Mapper.DynamicMap<List<User>>(db.Users); return users; } } 
+2
04 Sep '15 at 4:30
source share

Use the following namespace:

using System.Web.OData;

Instead:

using System.Web.Http.OData;

It worked for me

+2
Nov 03 '16 at 10:40
source share

Solution that worked for me:

  • Use [DataContract] for class attributes and [DataMember] for each property for serialization. This is enough to get a Json result (e.g. from fiddler).

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

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

  • Read this article, it helped me understand serialization: https://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization
+2
Nov 16 '16 at 7:07
source share

To add an answer to jensendp:

I would pass in the object of the model created by the user and use the values ​​from this object to set the values ​​in your newly created model. For example:

 public class UserInformation { public string Name { get; set; } public int Age { get; set; } public UserInformation(UserEntity user) { this.Name = user.name; this.Age = user.age; } } 

Then change your return type to: IEnumerable<UserInformation>

+1
May 05 '15 at
source share

This is my error

I basically add one line which they

  • entity.Configuration.ProxyCreationEnabled = false;

in UsersController.cs

 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using UserDataAccess; namespace SBPMS.Controllers { public class UsersController : ApiController { public IEnumerable<User> Get() { using (SBPMSystemEntities entities = new SBPMSystemEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Users.ToList(); } } public User Get(int id) { using (SBPMSystemEntities entities = new SBPMSystemEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Users.FirstOrDefault(e => e.user_ID == id); } } } } 

Here is my output:

+1
Apr 24 '19 at 9:36
source share

You need to define the Serializer Formatter in the WebApiConfig.cs file, available in the App_Start folder, for example

Adding config.Formatters.Remove (config.Formatters.XmlFormatter); // which will provide you with JSON data

Adding config.Formatters.Remove (config.Formatters.JsonFormatter); // which will provide you with XML data

+1
Jul 28 '19 at 11:47
source share

Another case when I received this error was that the database query returned null, but my user / view model type was set to invalid. For example, has the UserModel field changed from int to int? .

0
Oct 14 '15 at 2:49
source share

This also happens when the type of response is not public! I returned the inner class as I used Visual Studio to generate the type.

 internal class --> public class 
0
Nov 15 '17 at 15:52
source share

Although all of the answers above are correct, you can check InnerException> ExceptionMessage .

If he says something like this, "The ObjectContext instance has been deleted and can no longer be used for operations that require a connection ." This may be a problem due to the default behavior of EF.

By setting LazyLoadingEnabled = false in the DbContext constructor, we will achieve the goal.

 public class MyDbContext : DbContext { public MyDbContext() { this.Configuration.LazyLoadingEnabled = false; } } 

For a more detailed reading about EagerLoading and LazyLoading EF behavior, see this MSDN article .

0
Dec 29 '17 at 12:39 on
source share

In my case, I had a similar error message:

ObjectContent'1 was unable to serialize the response body for the content type application / xml; encoding = UTF-8 '.

But when I delved into it, the problem was:

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

The way I decided by adding KnownType .

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

This was decided based on this answer .

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

0
Feb 19 '18 at 12:21
source share

Visual Studio 2017 or 2019 does not think about this at all, since Visual Studio itself requires that the output be in json format, and the default Visual Studio format is " XmlFormat" (config.Formatters.XmlFormatter) .

Visual Studio should do this automatically, and not give developers so much trouble.

To fix this problem, go to the WebApiConfig.cs file and add

var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove (config.Formatters.XmlFormatter);

after " config.MapHttpAttributeRoutes (); " in the Register method (HttpConfiguration configuration) . This will allow your project to produce json output.

0
Apr 30 '19 at 20:27
source share

In my case, I decided to recreate the database. I made some changes to the model and, running Update-Database in the package manager console, I received the following error:

"The ALTER TABLE statement conflicts with the FOREIGN KEY constraint" FK_dbo.Activities_dbo.Projects_ProjectId ". The conflict occurred in the database" TrackEmAllContext-20190530144302 ", table" dbo.Projects ", column" Id "."

0
May 30 '19 at 14:46
source share

In case: if adding code to WebApiConfig.cs or Global.asax.cs does not work for you:

 .ToList(); 

Add the .ToList () function.

I tried every solution, but the following worked for me:

 var allShops = context.shops.Where(s => s.city_id == id)**.ToList()**; return allShops; 

I hope this helps.

0
Jun 05 '19 at 10:24
source share

Add line below

 this.Configuration.ProxyCreationEnabled = false; 

Two ways to use ProxyCreationEnabled as false .

  1. Add it to the DBContext constructor

     public ProductEntities() : base("name=ProductEntities") { this.Configuration.ProxyCreationEnabled = false; } 

OR

  1. Add a line inside the Get method

     public IEnumerable<Brand_Details> Get() { using (ProductEntities obj = new ProductEntities()) { this.Configuration.ProxyCreationEnabled = false; return obj.Brand_Details.ToList(); } } 
0
Jun 13 '19 at 5:55
source share

Use [Serializable] for the class:

Example:

 [Serializable] public class UserModel { public string Name {get;set;} public string Age {get;set;} } 

It worked for me!

0
Jul 22 '19 at 16:48
source share



All Articles