0

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?

2
  • 1
    Is it possible that your friends collection has a reference back to the user? In that case serialization will encounter a reference loop and cause an error Commented Mar 20, 2014 at 22:21
  • Thanks that's exactly what it was. Commented Mar 21, 2014 at 20:27

1 Answer 1

2

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; }        
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.