【发布时间】:2017-05-04 02:50:40
【问题描述】:
我很难找到解决此问题的方法。 我的 API 控制器无法获取我发布的数组的内容,并且总是返回 0 元素。
模型类:
public class Author
{
public int id { get; set; }
public int referenceId{ get; set; }
[Newtonsoft.Json.JsonIgnoreAttribute]
public virtual ICollection<AuthorBook> AuthorBooks { get; set; }
}
public class AuthorBook
{
public int authorId { get; set; }
public int bookId { get; set; }
}
API 控制器方法:
[Route("api/authorBooks")]
[HttpPost]
public IList getAuthorBooks(Author author)
{
return author.AuthorBooks.ToList();
}
JavaScript 客户端:
var auhtorItem =
{
"id": 8,
"referenceId" : 1 ,
"AuthorBooks": [{ authorId: 9, bookId : 23 }, { authorId: 9 , bookId : 25}]
};
return $.ajax({
url: booksUrl + "authorBooks",
type: 'POST',
data: JSON.stringify(auhtorItem ),
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
cache: false
});
我能够获取 id 和 referenceId 值,但是 AuthorBooks 是空的,并且计数是 0 而不是 2。
知道为什么吗?
【问题讨论】:
-
因为
Newtonsoft.Json.JsonIgnoreAttribute存在于AuthorBooks? -
这不是问题。 Newtonsoft.Json.JsonIgnoreAttribute 不应该出现在 AuthorBooks 上,但是,在您展示给我们的代码中。如果您在此处粘贴的代码与实际程序中的代码不同,edit此处的代码以匹配您的实际问题。
-
this is not the problem. Newtonsoft.Json.JsonIgnoreAttribute should not be present on AuthorBooks- 那为什么它会出现在代码片段中? -
嘿@degant你是对的!!!但我别无选择保留 Newtonsoft.Json.JsonIgnoreAttribute 否则当我想显示与作者相关的书籍时,我将有一个循环循环
-
@user708683 不幸的是,您必须将其删除。为了避免循环,您可以根据需要为请求/响应创建包装类
标签: c# json asp.net-web-api