Reputation: 1093
With Web API, when I return a simple object as below, everything works fine;
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[HttpGet]
[Route("UserInfo")]
public User GetUserInfo() {
string id = User.Identity.GetUserId();
User usr = db.Users.Find(id);
return user;
}
However, when I try and add child records to my object as below (a User has a list of AppUserInfo objects in the 'Friends' collection) then I can see the API return a User with a populated list (as expected) but I receive 'null' content on the client.
User user = db.Users
.Where(u => u.Id == id)
.Include(u => u.Friends)
.FirstOrDefault();
return user;
I am trying to call this on the client as such but am receiving an error of 'null' content and 'response.IsSuccessStatusCode' is false. Its like it is having problems serialising the child collection perhaps?
var response = await client.GetAsync("api/Account/UserInfo");
Can anyone explain why this occurs?
Upvotes: 0
Views: 1353
Reputation: 1093
Answer provided by Kenneth.
The secondary object had a reference back to the parent object, causing the serialisation to break.
Eg:
public class User {
public int UserId { get; set; }
public string name { get; set; }
public List<UserInfo> Infos { get; set; }
}
public class UserInfo {
public int UserInfoId { get; set; }
[ForeignKey]
public int UserId { get; set; }
public User user { get; set; }
}
Upvotes: 2