Failed to serialize the response in Web API with Json
When it comes to returning data back to the consumer from Web Api (or any other web service for that matter), I highly recommend not passing back entities that come from a database. It is much more reliable and maintainable to use Models in which you have control of what the data looks like and not the database. That way you don't have to mess around with the formatters so much in the WebApiConfig. You can just create a UserModel that has child Models as properties and get rid of the reference loops in the return objects. That makes the serializer much happier.
Also, it isn't necessary to remove formatters or supported media types typically if you are just specifying the "Accepts" header in the request. Playing around with that stuff can sometimes make things more 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.
}
Failed to serialize the response body for content type
The IdentityEqualityCompairer
in the NHibernate framework appears to have the [SerializableAttribute]
annotation.
Taken from a comment on an answer here Why won't Web API deserialize this but JSON.Net will? it looks like JSON.NET is configured a little differently between WebApi usage and it's standalone usage.
Json.NET serializer by default set the IgnoreSerializableAttribute to true. In WebAPI, we set that to false.
So given you cannot take the [SerializableAttribute]
off (as it is not within your code) you could try changing the default WebApi JSON.NET setting to ignore it using this answer here:
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
Perhaps also consider Using a DTO for your results being sent over in the response - this will give you full control over the object being sent over the wire.
Web API: Failed to serialize the response body for content type
The problem looks to be that, in certain situations, you are returning from WriteJson()
without writing anything, specifically when customType.TimeZone == null
:
var customType = (CustomType)value;
if (customType == null || null== customType.TimeZone) return;
Doing so will result in an invalid JSON object, because the property name will already have been written by the caller, resulting in:
{
"customType":
}
Trying to do this results in the exception you are seeing.
Instead, you need to prevent the property itself from being serialized. That's not possible in the converter however, it needs to be done in the containing type.
To avoid serializing a property with a null value, you should set NullValueHandling = NullValueHandling.Ignore
in serializer settings, or on the property itself:
public class ContainerClass
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CustomType CustomType { get; set; }
}
To prevent serializing your property when its TimeZone
property is null, you should use conditional property serialization by adding a ShouldSerializeXXX()
method to the containing type, where XXX
exactly matches your property name:
public class ContainerClass
{
public CustomType CustomType { get; set; }
public bool ShouldSerializeCustomType()
{
return CustomType != null && CustomType.TimeZone != null;
}
}
Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'
I would suggest Disable Proxy Creation only in the place where you don't need or is causing you trouble. You don't have to disable it globally you can just disable the current DB context via code...
[HttpGet]
[WithDbContextApi]
public HttpResponseMessage Get(int take = 10, int skip = 0)
{
CurrentDbContext.Configuration.ProxyCreationEnabled = false;
var lista = CurrentDbContext.PaymentTypes
.OrderByDescending(x => x.Id)
.Skip(skip)
.Take(take)
.ToList();
var count = CurrentDbContext.PaymentTypes.Count();
return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count });
}
Here I only disabled the ProxyCreation in this method, because for every request there is a new DBContext created and therefore I only disabled the ProxyCreation for this case .
Hope it helps
Always have error The ObjectContent 1 type failed to serialize the response body...
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.
Related Topics
Catch Exception That Is Thrown in Different Thread
What Does the '=>' Syntax in C# Mean
Cursor.Current VS. This.Cursor
"A Project with an Output Type of Class Library Cannot Be Started Directly"
How to Run an Exe Program from a Windows Service Using C#
C# Member Variable Initialization; Best Practice
How to Determine Programmatically Whether a Particular Process Is 32-Bit or 64-Bit
Deserializing JSON Object Array with JSON.Net
When Should I Dispose of a Data Context
Difference Between Events and Delegates and Its Respective Applications
How to Read a Pem Rsa Private Key from .Net
Converting a .Net Func<T> to a .Net Expression<Func<T>>
Why Can't I Unbox an Int as a Decimal