我一直在寻找这个相对简单的任务的答案,但没有成功。所以我想在这里问我的问题。我有一个简单的数据库,里面有两个表,Books和Authors。
我得到了由ADO.NET实体数据模型生成的模型。这是自动生成的Books模型:
public partial class Book
{
public int BookID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int ISBN { get; set; }
public int AuthorID { get; set; }
public virtual Author Author { get; set; }
}
这是自动生成的Authors模型:
public partial class Author
{
public Author()
{
this.Books = new HashSet<Book>();
}
public int AuthorID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
这是控制器的一部分,该控制器是用于获取JSON格式的所有书籍列表的方法。
// api/books
public IQueryable<Book> GetBooks()
{
// return db.Books.Include(x => x.Authors); Don't work
return db.Books;
}
这是我用于调用端点的JS:
$.getJSON("api/books")
.done(function (data) {
console.log(data);
})
.fail(function (xhr) { console.log(xhr.responseText) });
没什么,只是尝试发出GET请求并接收所有书籍及其相关作者的清单。
这是错误消息的一部分:
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected for property 'Author' with type 'System.Data.Entity.DynamicProxies.Author_5968F94A1BBB745A30D62CD59D0AC5F96A198B3F16F0EA2C2F61575F70034886'. Path '[0].Books[0]'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"
我曾尝试在JSON中保留对象引用,但是这样会破坏响应。那是唯一的选择吗?
如果检查内部异常,它将显示:
Self referencing loop detected for property 'Author'
这告诉您,您的Author类引用返回了父类(即,反之亦然)。
在您的Web API配置(App_Start/WebApiConfig.cs
)中,添加以下内容:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Prevent "Self referencing loop detected" error occurring for recursive objects
var serializerSettings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
config.Formatters.JsonFormatter.SerializerSettings = serializerSettings;
}
}
这告诉JSON.NET忽略引用父对象的嵌套对象
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句