If I have a Customer class that just has simple properties (e.g. Name, etc.) then I can create a CustomersController that derives from ApiController, and query my Customer objects using the URL /api/customers.
Similarly, if I have an Order class with simple properties (Description, Amount) then I can create an OrdersController and access it in the same way.
However, if I then add a property to my Customer class that lists the Orders associated with that Customer:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
// ...
public virtual ICollection<Order> Orders { get; set; }
}
...then when I try to query using /api/customers I get a 500 Server Error. I can put a breakpoint within the CustomersController and can see that it does call the correct method, and attempts to return a value. However, somewhere in the guts of the framework it fails to turn that into an HTTP response.
It looks like it cannot serialize the Orders information and/or package it up for the HTTP response, but I'm not sure what I need to do to make this happen. Or is it simply the case that the WebApi stuff is not designed to return complex objects?
Update: my code is here: https://gist.github.com/43ed2f29f8adfb44cef6
Update 2: more information on the error I get:
Server error The website encountered an error while retrieving http://localhost:1031/api/customers/6.It may be down for maintenance or configured incorrectly. Here are some suggestions: Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
The Intellitrace log shows the following: https://i.stack.imgur.com/8R1XL.png
[I can hardly believe that the Intellitrace window does not allow me to copy the text, so that I had to actually print-screen and upload an image. What year is this?]
Related: ASP.Net Web API showing correctly in VS but giving HTTP500