【问题标题】:Controller.json set Serialization.ReferenceLoopHandlingController.json 设置 Serialization.ReferenceLoopHandling
【发布时间】:2016-01-20 05:55:04
【问题描述】:

有没有办法设置 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);
        });

【问题讨论】:

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    在 Startup 类的 ConfigureServices 方法中试试这个:

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

    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;
    });
    

    【讨论】:

    • 核心的替代形式:services.AddMvcCore() .AddJsonFormatters(j =&gt; j.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
    【解决方案3】:

    这对我来说适用于 .NET Core 3.0。

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

    【讨论】:

    • 我必须添加对Microsoft.AspNetCore.Mvc.NewtonsoftJson的 NuGet 引用
    猜你喜欢
    • 2021-06-09
    • 2016-03-30
    • 1970-01-01
    • 2012-05-18
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 2015-04-02
    相关资源
    最近更新 更多