【问题标题】:A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Item序列化“System.Data.Entity.DynamicProxies.Item”类型的对象时检测到循环引用
【发布时间】:2020-11-18 13:02:20
【问题描述】:

我正在尝试做一个简单的 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 异常,如本问题的标题所示。

这是一个错误还是我的实现?

【问题讨论】:

  • 你用的是哪个json库?

标签: c# ajax asp.net-mvc


【解决方案1】:

不,这不是错误,实际上问题不在于您的实现。问题在于返回模型的结构。

您可以将您的模型转换为其他模型而无需手动引用,例如。

var data = _unitOfWork.Items.GetItems().Select(x => new { ... });

或者根据您使用的 json 序列化程序,您可以打开忽略循环引用。

Newtonsoft.json 示例

services
  .AddMvc()
  .AddJsonOptions(jsonOptions => { jsonOptions.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; } );

一些more insight 用于 System.Text.Json 库。

【讨论】:

  • 我怎样才能通过细节忽略循环引用
  • 请在我的代码中写下这一行services .AddMvc() .AddJsonOptions(jsonOptions =&gt; { jsonOptions.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; } );
  • 在您的 Startup.cs 中。我不确定您使用的是哪个 .net/.net 核心版本(以及哪个 json 序列化程序)。
  • 我使用 json 版本 6 和 .net mvc
  • 抱歉,错过了那部分。我的答案是针对 .net core
猜你喜欢
  • 2012-05-04
  • 2012-12-01
  • 1970-01-01
  • 2015-01-21
  • 2010-11-12
  • 2013-04-23
  • 2010-10-14
  • 1970-01-01
相关资源
最近更新 更多