Controller.json设置Serialization.ReferenceLoopHandling

Iva*_*Rep 6 asp.net-core-mvc asp.net-core

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

当解析具有两端定义的导航属性的实体时,它当前正在引发自引用循环.通过设置解决了这个问题

ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Run Code Online (Sandbox Code Playgroud)

有没有办法为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);
        });
Run Code Online (Sandbox Code Playgroud)

Tan*_*ato 14

我认为一个更漂亮的解决方案是在您的ConfigureServices中添加JsonOptions,如:

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = 
                               Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Run Code Online (Sandbox Code Playgroud)


Jim*_*non 2

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

在 Startup 类的 ConfigureServices 方法中尝试一下:

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

或者

services.AddMvc(options =>
{
    var jsonOutputFormatter = options.OutputFormatters.SingleOrDefault(f => f.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter;
    if (jsonOutputFormatter != null)
        jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Run Code Online (Sandbox Code Playgroud)

  • 核心的替代形式:`services.AddMvcCore() .AddJsonFormatters(j =&gt; j.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)` (3认同)