I have an abstract superClass "Publication" that has two derived classes Auction and Purchase. Also I have a class category that has a list of Publications.
In my Rest Server side I send the a list of Category, in the client side I receive this list of Category and try to cast the object as a list of Categories. The problem is when I try to cast the object I get the follow error :
Could not create an instance of type FrontOffice.Models.Publication. Type is an interface or abstract class and cannot be instantiated. Path '[0].Publications[0].Price'
I will paste below of this, the code that I am using.
//Rest Server Controller
public IEnumerable<Category> GetAllCategory() {
return listCategory;
}
//Category Class
public class Category {
public string Name { get; set; }
public List<Publication> Publications { get; set; }
}
//Publication Entity
[DataContract]
[KnownType(typeof(Auction))]
[KnownType(typeof(Buyout))]
public abstract class Publication {
[DataMember]
public int PublicationID { get; set; }
[DataMember]
public string Title { get; set; }
public Publication() {}
public Publication(int PublicationID, string Title, string Description) {
this.PublicationID = PublicationID;
this.Title = Title;
}
}
And in the client side I do :
List<Category> listCategory = new List<Category>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:50687/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("Application/json"));
HttpResponseMessage response = client.GetAsync("api/categories/GetAllcategory").Result;
if (response.IsSuccessStatusCode) {
listCategory = response.Content.ReadAsAsync<List<Category>>().Result;
}
I am getting the error in the line that I try to instance listCategory.
The reason you are getting an
AggregateException
is because you are calling an async method (ReadAsAsync
):In async code, you can (sort of) run multiple parallel lines of code. Any one of these lines of code can throw an exception, and due to this nature, async methods that throw exceptions will throw an
AggregateException
. The purpose of this exception is to collect, or aggregate, all of the exceptions that could have been thrown by "parallel" lines of code.However as @Matthew Haugen points out, 99% of your AggregateExceptions will just wrap a single exception. What you have to do is
Bottom line is that the problem could be one of many things in your code, and more information is needed to solve it. Since the exception happens only when
Category.Publications
is not null, I wonder are you using EntityFramework with lazy loading? If so, it could be an issue with the foreign key between Category and Publication. But that's just a stab in the dark.