Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Simplest example of this, I get a collection and try to output it via Web API:

// GET api/items public IEnumerable<Item> Get() {     return MyContext.Items.ToList(); } 

And I get the error:

Object of type
'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]' cannot be converted to type
'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'

This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:

MyContext.Configuration.ProxyCreationEnabled = false; 

But that defeats the purpose of a lot of what I am trying to do. Is there a better way?

like image 754
naspinski Avatar asked Dec 19 '12 18:12

naspinski


2 Answers

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

like image 152
visar_uruqi Avatar answered Sep 18 '22 15:09

visar_uruqi


if you have navigation properties and you do not want make them non virtual, you should using JSON.NET and change configuration in App_Start to using JSON not XML!
after install JSON.NET From NuGet, insert this code in WebApiConfig.cs in Register method

var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter); 
like image 43
Mahdi Avatar answered Sep 19 '22 15:09

Mahdi