【发布时间】:2015-01-28 05:43:22
【问题描述】:
上下文很长,所以我将从以下问题开始:为什么 InductionQAs 集合属性没有被重新水化?
在 Web API 2 方法中,LINQ 生成一个对象 ic,其集合属性为 InductionQAs。在我消除了一个巨大的不相关对象图并防止循环引用之后,该方法返回了ic。这是代码。为简洁起见,已删除错误处理。
// GET: api/InductionContent/5
[Authorize]
public object Get(int id)
{
var dc = new Models.InductionsDataContext();
var user = GetUser(dc);
var ic = dc.InductionContents.Single(c => c.InductionContentID == id);
ic.User.InductionContents.Clear(); //don't ship this it can be huge
return ic;
}
这是调用 JS 代码。忽略授权头业务,一切正常。
var token, headers;
$.ajax({ //get session token
url: "api/token",
headers: { Authorization: "Basic " + btoa("username:password") },
}).done(function (result) {
localStorage.setItem('access_token', token = result.access_token);
var headers = { Authorization: "Session " + token };
$.ajax({ //get an induction content object
url: "api/InductionContent/5",
headers: headers
}).done(function (ic) {
//at this point we have an object graph
var json = JSON.stringify(ic);
});
});
这是 JSON.stringify(ic) 返回的内容:
{
"InductionContentID": 5,
"InductionTemplateID": 1,
"InductionContent1": "<p>We recognise that it is ...(redacted)</p>",
"InductionContentOrder": 301,
"Caption": "Workplace Health and Safety",
"OwnerId": 0,
"ParentId": 0,
"TopicId": 5,
"InductionQAs": [
{
"InductionQAID": 1,
"InductionContentID": 5,
"Question": "Who is responsible for ...(redacted)",
"Answers": "A|B|C|*D",
"InductionQAOrder": 1
}
],
"User": null
}
一切顺利。现在我们来回它。
$.ajax({
type: "post",
url: "api/InductionContent",
headers: headers,
data: ic
});
这会调用以下网络方法:
// POST: api/InductionContent
[Authorize]
public void Post([FromBody]Models.InductionContent ic)
{
//redacted
}
方法被调用并且ic 有一个值。 ic.User 包含数据,但检查 ic.InductionQAs 发现它尚未初始化。
序列化配置如下:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.MessageHandlers
.Add(new AuthenticationHandler(CreateConfiguration()));
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
【问题讨论】:
标签: ajax json serialization asp.net-web-api2