0

I'm working on a WebApi project and I want to serialize a List<User> and send it back to the user. But it just returns [{"$id":"1"}] where User is an entity which was generated by Entity Framework database-first models classes.

Controller:

public List<User> GetAllUsers() 
{ 
   List<User> Users = Common.Framework.Persistence.PersistSvr<Business.Entity.User>
                     .GetAll().ToList(); 
  return Users; 
}

Here is the User class:

 public partial class User
 {
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
      public User()
      {
          this.ContentLikes = new HashSet<ContentLikes>();
          this.ContentPermission = new HashSet<ContentPermission>();
          this.File = new HashSet<File>();
          this.FolderPermission = new HashSet<FolderPermission>();
          this.SiteUsers = new HashSet<SiteUsers>();
          this.UserGroup = new HashSet<UserGroup>();
      }

      public long ID { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Email { get; set; }
      public string UserName { get; set; }
      public string Password { get; set; }
      public Nullable<long> DiskUsed { get; set; }
      public Nullable<long> DiskUsage { get; set; }
      public Nullable<bool> Status { get; set; }

      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<ContentLikes> ContentLikes { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<ContentPermission> ContentPermission { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<File> File { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<FolderPermission> FolderPermission { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<SiteUsers> SiteUsers { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<UserGroup> UserGroup { get; set; }
 }

I have added these lines of codes to WebApiConfig.cs File.

 var json = config.Formatters.JsonFormatter;
 json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
 config.Formatters.Remove(config.Formatters.XmlFormatter);

it just resolved double serialization. and i have my old problem. i will receive $id : "1" when i send a request to my ActionMethod.

i have learned that it's because of EntityFramework. because WebApi doesn't able to serialize an EntityFramework Entity (i think it's because of relations that exists in my Models)

so what should i do to solve it ? I don't want to rewrite them all.

RezaNoei
  • 1,266
  • 1
  • 8
  • 24
  • 1
    post your apicontroller method too – Sumit raj May 29 '18 at 17:11
  • Looks like you are manually serialising to JSON but returning XML. Show us how you are doing this. – DavidG May 29 '18 at 17:11
  • @RezaNoei The first thing you need to do is configure web api to return json, get rid of your double serialization too: https://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome – RandomUs1r May 29 '18 at 17:32
  • Here is My Controller : public JsonResult> GetAllUsers() { List Users = Common.Framework.Persistence.PersistSvr.GetAll().ToList(); return Json(Users); } – RezaNoei May 29 '18 at 17:38
  • When i removed JsonResult from my Controller. i have got an error : `The 'ObjectContent 1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.` – RezaNoei May 29 '18 at 17:47

1 Answers1

0

Try this

public IHttpActionResult GetAllUsers()
        {
            try
            {
                List<User> Users = Common.Framework.Persistence.PersistSvr<Business.Entity.User>
                                   .GetAll().ToList(); 
                return Ok(Users);

            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.Message);

            }
        }

You will get response in users as json along with status code.

Sumit raj
  • 821
  • 1
  • 7
  • 14
  • When i removed JsonResult from my Controller. i have got an error : `The 'ObjectContent 1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.` – RezaNoei May 29 '18 at 17:49
  • don't remove `JsonResult` instead `>` – Sumit raj May 29 '18 at 17:49
  • When do this i will get another problem : `Using the generic type 'JsonResult' requires 1 type arguments` – RezaNoei May 29 '18 at 17:52
  • I think, the real problem is about `Entityframework` I will Explain it in an Answer. – RezaNoei May 29 '18 at 17:58
  • Sorry i checked you were right. In API , it does require, anyway i have altered my solution and it will work. – Sumit raj May 29 '18 at 18:00
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172016/discussion-between-sumit-raj-and-rezanoei). – Sumit raj May 29 '18 at 18:02