0

I have a web API controller method that is returning an object which is giving the client a 500 internal server error. On the server, the output windows says "Newtonsoft.Json.JsonSerializationException". But I cannot see anything wrong with the class I am returning.. and I am sure this has historically been working. Any help would be greatly appreciated!

EDIT: Is this a problem with the web API not being able to serialize a 'dynamic entity'? The code that generates the class is here:

        var id = User.Identity.GetUserId();

        var user = db.Users
                    .Where(u => u.Id == id)
                    .Include(u => u.Friends)
                    .FirstOrDefault();

        return user;

I am returning the following class;

   public class User : IdentityUser
{
    public User()
    {
        this.Friends = new List<UserFriend>();
    }

    public string PhoneNumber { get; set; }
    public string Email { get; set; }
    public List<UserFriend> Friends { get; set; }
    public bool HasRegistered { get; set; }
    public string LoginProvider { get; set; }
}

The 'UserFriend' class looks like this;

    public class UserFriend
{
    public int UserFriendId { get; set; }
    public string Id { get; set; }
    public string FriendUserId { get; set; }
    public string FriendUserName { get; set; }
    public string FriendPhoneNumber { get; set; }

}

Strangely, when I hover over the returned object on the server, the type is: {System.Data.Entity.DynamicProxies.User_7283E76A736B4DD47E89120E932CD5C04B62F84C316961F02CDAE3EEF4786504}. I am not sure what this is.. :-O

creatiive
  • 1,073
  • 21
  • 49
  • 1
    Could you add full exception message? To me it looks like you have a circular reference User -> UserFriend -> User, something similar to http://stackoverflow.com/questions/19664257/why-in-web-api-returning-an-entity-that-has-a-one-to-many-relationship-causes-an – b2zw2a Nov 10 '14 at 21:49
  • This is the only error text I get. And I have included the UserFriend class above and you can see there is no circular reference. – creatiive Nov 11 '14 at 09:59

1 Answers1

1

I used AutoMapper to create a DTO instead of just returning the User class. The DynamicProxies class is because the query uses lazy loading and it has not got the object yet.

After installing automapper (Install-Package AutoMapper);

        Mapper.CreateMap<User, UserDto>();
        UserDto dto = Mapper.DynamicMap<UserDto>(user);

Then return the dto.

creatiive
  • 1,073
  • 21
  • 49
  • I upvoted this answer because I'm having this issue where serializing entities with complex entities to JSON sometimes fails, I think this tool will help out a lot. – Francis Ducharme Nov 11 '14 at 15:46