I’m writing an ASP.NET Web API project with 3 controllers
- HomeController
- LaureatesController
- PrizesController
When I try to call GET method GetPrizes() from Postman or the web, I’m getting this error
The ‘ObjectContent`1’ type failed to serialize the response body for content type ‘application/json; charset=utf-8’
My DB and PrizesController:
private ApplicationDbContext db = new ApplicationDbContext();
public IEnumerable<object> GetPrizes()
{
var prizes = db.Prizes.ToList()
.Select(prize => new
{
prize.PrizeID,
prize.Category,
prize.Year,
Laureates = prize.Laureates.Select(Laureate => new
{
Laureate.LaureateID,
Laureate.Surname,
Laureate.FirstName,
Laureate.Gender,
Laureate.Born,
Laureate.BornCountry,
Laureate.Died
})
});
return db.Prizes;
}
I have added in the webApiconfig.cs file:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
and my Global.ASAX contains:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Do you have any Idea on what is wrong here and I’m getting that error?
>Solution :
The error message "The ‘ObjectContent1’ type failed to serialize the response body for content type ‘application/json; charset=utf-8’" usually indicates that there is an issue with the object being returned by the API action. In this case, it seems that the problem is with the prizes variable in theGetPrizes` action.
The prizes variable is a collection of anonymous objects, which cannot be serialized to JSON by default. To fix this issue, you can either create a class to represent the data you want to return in the API response, or you can use the JsonResult class to return the data as a JSON object.
Here’s an example of how you can use the JsonResult class to return the data:
public JsonResult GetPrizes()
{
var prizes = db.Prizes.ToList().Select(prize => new
{
prize.PrizeID,
prize.Category,
prize.Year,
Laureates = prize.Laureates.Select(Laureate => new
{
Laureate.LaureateID,
Laureate.Surname,
Laureate.FirstName,
Laureate.Gender,
Laureate.Born,
Laureate.BornCountry,
Laureate.Died
})
}
);
return Json(prizes, JsonRequestBehavior.AllowGet);
}
Alternatively, you can create a class to represent the data you want to return, like this:
public class PrizeDTO
{
public int PrizeID { get; set; }
public string Category { get; set; }
public int Year { get; set; }
public IEnumerable<LaureateDTO> Laureates { get; set; }
}
public class LaureateDTO
{
public int LaureateID { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public string Gender { get; set; }
public DateTime Born { get; set; }
public string BornCountry { get; set; }
public DateTime Died { get; set; }
}
Then, you can return an instance of this class from the API action:
public IEnumerable<PrizeDTO> GetPrizes()
{
var prizes = db.Prizes.ToList().Select(prize => new PrizeDTO
{
PrizeID = prize.PrizeID,
Category = prize.Category,
Year = prize.Year,
Laureates = prize.Laureates.Select(Laureate => new LaureateDTO
{
LaureateID = Laureate.LaureateID,
Surname = Laureate.Surname,
FirstName = Laureate.FirstName,
Gender = Laureate.Gender,
Born = Laureate.Born,
BornCountry = Laureate.BornCountry,
Died = Laureate.Died
})
});
return prizes;
}
Either of these approaches should fix the serialization issue and allow the API action to return the data as a JSON object.