Asp.net core Controller.json set Serialization.ReferenceLoopHandling

Asp.net core Controller.json set Serialization.ReferenceLoopHandling,asp.net-core,asp.net-core-mvc,Asp.net Core,Asp.net Core Mvc,有没有办法设置Controller.Json ReferenceLoopHandling属性 当前,在解析两端都定义了导航属性的实体时,它会导致自引用循环。这个问题通过设置 ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 对于Controller.Json方法,有没有办法做到这一点 我找到了这段代码,但它似乎不起作用 services.Configure<MvcOptions>(option

有没有办法设置Controller.Json ReferenceLoopHandling属性

当前,在解析两端都定义了导航属性的实体时,它会导致自引用循环。这个问题通过设置

ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
对于Controller.Json方法,有没有办法做到这一点

我找到了这段代码,但它似乎不起作用

services.Configure<MvcOptions>(option =>
        {
            option.OutputFormatters.Clear();
            var jsonOutputFormatter = new JsonOutputFormatter();
            jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            option.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
services.Configure(选项=>
{
option.OutputFormatters.Clear();
var jsonOutputFormatter=新的jsonOutputFormatter();
jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore;
option.OutputFormatters.Insert(0,jsonOutputFormatter);
});

这个问题是很久以前提出来的,但它仍然可以帮助其他人

在Startup类的ConfigureServices方法中尝试以下操作:

services.AddMvc(options =>
{
    ((JsonOutputFormatter)options.OutputFormatters.Single(f => f.GetType() == typeof(JsonOutputFormatter))).SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});


我认为一个更好的解决方案是在配置服务中添加JSONOption,如:

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

这在.NETCore3.0中对我很有效

services.AddMvcCore().AddNewtonsoftJson(
    options => options.SerializerSettings.ReferenceLoopHandling =
        Newtonsoft.Json.ReferenceLoopHandling.Ignore);

尝试按照.core的替代形式:
services.AddMvcCore().AddJsonFormatters(j=>j.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore)
services.AddMvcCore().AddNewtonsoftJson(
    options => options.SerializerSettings.ReferenceLoopHandling =
        Newtonsoft.Json.ReferenceLoopHandling.Ignore);