(WebApi) 无法将对象集合序列化为 Json
(WebApi) Can't serialize collection of objects to Json
在我的 WebApi 控制器中,我有一些方法 return 从数据库中检索的对象被序列化为 Json。如果方法序列化并且 return 只有一个对象,则一切正常,但在尝试序列化对象集合时失败。
这是我的模型class:
[Table("Athlete")]
public partial class Athlete
{
public Athlete()
{
Event = new HashSet<Event>();
User = new HashSet<User>();
}
[Required]
[StringLength(32)]
[DisplayName("First name")]
public string FirstName { get; set; }
[Required]
[StringLength(32)]
[DisplayName("Last name")]
public string LastName { get; set; }
[StringLength(32)]
[DisplayName("Sport")]
public string Sport { get; set; }
[Key]
[Column(TypeName = "numeric")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal Athlete_ID { get; set; }
[DataMember]
[Column(TypeName = "numeric")]
public decimal? Team_Team_ID { get; set; }
[NotMapped]
[DisplayName("Team")]
public string TeamName { get; set; }
[JsonIgnore]
public virtual Team Team { get; set; }
[JsonIgnore]
public virtual ICollection<Event> Event { get; set; }
[JsonIgnore]
public virtual ICollection<User> User { get; set; }
}
这很好用:
[HttpGet]
public IHttpActionResult GetById(int id)
{
var athlete = _db.Athlete
.Where(a => a.Athlete_ID == id)
.FirstOrDefault();
if (athlete != null)
{
return Json<Athlete>(athlete);
}
return NotFound();
}
以下方法导致序列化错误(System.InvalidOperationException)
('ObjectContent`1' 类型无法序列化内容类型 'application/json; charset=utf-8' 的响应正文。)
内部异常的消息是"Self referencing loop detected for property 'ApplicationInstance' with type 'ASP.global_asax'. Path 'Request.Properties.MS_HttpContext.ApplicationInstance.Context'."
[HttpGet]
public IHttpActionResult GetAllAthletes()
{
var athletes = _db.Athlete.ToArray();
if (athletes != null)
{
return Ok(Json<IEnumerable<Athlete>>(athletes));
}
return NotFound();
}
我已经尝试像在 this question 中那样更改 WebApiConfig.cs 中的序列化设置,但到目前为止没有任何效果。
如有任何帮助,我们将不胜感激。
我设法找到了一种半优雅的解决方法。我对此并不完全满意,但男人必须做男人必须做的事。
万一以后有人需要这个:
创建一个实现 IHttpActionResult 接口的 class:
public class MyJsonResult : IHttpActionResult
{
object _value;
HttpRequestMessage _request;
public MyJsonResult(object value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(_value), Encoding.UTF8, "application/json"),
RequestMessage = _request,
StatusCode = HttpStatusCode.OK
};
return Task.FromResult(response);
}
}
然后按如下方式使用:
[HttpGet]
public IHttpActionResult GetAllAthletes()
{
var athletes = _db.Athlete;
if (athletes != null)
{
return new MyJsonResult(athletes, Request);
}
return NotFound();
}
在我的 WebApi 控制器中,我有一些方法 return 从数据库中检索的对象被序列化为 Json。如果方法序列化并且 return 只有一个对象,则一切正常,但在尝试序列化对象集合时失败。
这是我的模型class:
[Table("Athlete")]
public partial class Athlete
{
public Athlete()
{
Event = new HashSet<Event>();
User = new HashSet<User>();
}
[Required]
[StringLength(32)]
[DisplayName("First name")]
public string FirstName { get; set; }
[Required]
[StringLength(32)]
[DisplayName("Last name")]
public string LastName { get; set; }
[StringLength(32)]
[DisplayName("Sport")]
public string Sport { get; set; }
[Key]
[Column(TypeName = "numeric")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal Athlete_ID { get; set; }
[DataMember]
[Column(TypeName = "numeric")]
public decimal? Team_Team_ID { get; set; }
[NotMapped]
[DisplayName("Team")]
public string TeamName { get; set; }
[JsonIgnore]
public virtual Team Team { get; set; }
[JsonIgnore]
public virtual ICollection<Event> Event { get; set; }
[JsonIgnore]
public virtual ICollection<User> User { get; set; }
}
这很好用:
[HttpGet]
public IHttpActionResult GetById(int id)
{
var athlete = _db.Athlete
.Where(a => a.Athlete_ID == id)
.FirstOrDefault();
if (athlete != null)
{
return Json<Athlete>(athlete);
}
return NotFound();
}
以下方法导致序列化错误(System.InvalidOperationException) ('ObjectContent`1' 类型无法序列化内容类型 'application/json; charset=utf-8' 的响应正文。)
内部异常的消息是"Self referencing loop detected for property 'ApplicationInstance' with type 'ASP.global_asax'. Path 'Request.Properties.MS_HttpContext.ApplicationInstance.Context'."
[HttpGet]
public IHttpActionResult GetAllAthletes()
{
var athletes = _db.Athlete.ToArray();
if (athletes != null)
{
return Ok(Json<IEnumerable<Athlete>>(athletes));
}
return NotFound();
}
我已经尝试像在 this question 中那样更改 WebApiConfig.cs 中的序列化设置,但到目前为止没有任何效果。
如有任何帮助,我们将不胜感激。
我设法找到了一种半优雅的解决方法。我对此并不完全满意,但男人必须做男人必须做的事。
万一以后有人需要这个:
创建一个实现 IHttpActionResult 接口的 class:
public class MyJsonResult : IHttpActionResult
{
object _value;
HttpRequestMessage _request;
public MyJsonResult(object value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(_value), Encoding.UTF8, "application/json"),
RequestMessage = _request,
StatusCode = HttpStatusCode.OK
};
return Task.FromResult(response);
}
}
然后按如下方式使用:
[HttpGet]
public IHttpActionResult GetAllAthletes()
{
var athletes = _db.Athlete;
if (athletes != null)
{
return new MyJsonResult(athletes, Request);
}
return NotFound();
}