【问题标题】:WebApi can't serialize Entity Framework entitiesWebApi 无法序列化 Entity Framework 实体
【发布时间】:2018-05-29 17:07:21
【问题描述】:

我正在开发一个 WebApi 项目,我想序列化 List<User> 并将其发送回用户。但它只返回[{"$id":"1"}],其中User 是由实体框架数据库优先模型类生成的实体。

控制器:

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

这是User 类:

 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; }
 }

我已将这几行代码添加到 WebApiConfig.cs 文件中。

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

它刚刚解决了双重序列化。我有我的老问题。 当我向我的 ActionMethod 发送请求时,我将收到 $id : "1"

我了解到这是因为 EntityFramework。因为 WebApi 无法序列化 EntityFramework 实体(我认为这是因为我的模型中存在关系)

那么我应该怎么做才能解决它? 我不想全部重写。

【问题讨论】:

  • 也发布你的 apicontroller 方法
  • 看起来您正在手动序列化为 JSON 但返回 XML。向我们展示您是如何做到这一点的。
  • @RezaNoei 你需要做的第一件事是配置web api返回json,也摆脱你的双重序列化:stackoverflow.com/questions/9847564/…
  • 这是我的控制器: public JsonResult> GetAllUsers() { List Users = Common.Framework.Persistence.PersistSvr.GetAll()。列表();返回 Json(用户); }
  • 当我从控制器中删除 JsonResult 时。我有一个错误:The 'ObjectContent 1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

标签: c# entity-framework asp.net-web-api


【解决方案1】:

试试这个

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);

            }
        }

您将在用户中以 json 格式获得响应以及状态码。

【讨论】:

  • 当我从控制器中删除 JsonResult 时。我有一个错误:The 'ObjectContent 1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
  • 不要删除JsonResult,而是删除&lt;List&lt;User&gt;&gt;
  • 什么时候这样做我会遇到另一个问题:Using the generic type 'JsonResult&lt;T&gt;' requires 1 type arguments
  • 我认为,真正的问题是关于Entityframework 我将在答案中解释。
  • 对不起,我检查你是对的。在 API 中,它确实需要,无论如何我已经改变了我的解决方案并且它会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多