![](/img/trans.png)
[英]A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies
[英]A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Item
我正在嘗試做一個簡單的 JSON 返回,但我遇到了以下問題。
[HttpGet]
public JsonResult GetItemsEdit()
{
try
{
var data = _unitOfWork.Items.GetItems();
return Json(new
{
data
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
這是我的ajax調用代碼:
// Gets Items on Dropdown
$.ajax({
type: "GET",
url: "/Payments/GetItemsEdit",
datatype: "application/json",
success: function (data) {
debugger
alert("ok");
$.each(data, function (index, value) {
$('#Item').append('<option value="' + value.Id + '">' + value.itemName + '</option>');
});
},
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
});
我得到一個 HTTP 500 異常,如這個問題的標題所示。
這是錯誤還是我的實現?
不,這不是錯誤,實際上問題不在於您的實現。 問題是返回模型的結構。
您可以將模型轉換為不同的模型而無需手動參考,例如。
var data = _unitOfWork.Items.GetItems().Select(x => new { ... });
或者根據您使用的 json 序列化程序,您可以打開忽略循環引用。
Newtonsoft.json 的示例
services
.AddMvc()
.AddJsonOptions(jsonOptions => { jsonOptions.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; } );
System.Text.Json 庫的更多見解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.