未应用MVC AddJsonOptions ReferenceLoopHandling配置

Cra*_*aig 1 c# json.net asp.net-core asp.net-core-webapi

我有另一个ASP.NET Core 2/Angular 2应用程序使用的ASP.NET Core 2 API C#项目.我已经将API项目MVC服务JSON选项配置ReferenceLoopHandlingIgnore例如

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

但是,当我运行我的应用程序时,我仍然从我的一个HTTP GET方法中得到"检测到自我引用循环..."错误.

在调试模式下,如果我在序列化结果之前暂停方法并手动运行序列化,例如

?Newtonsoft.Json.JsonConvert.SerializeObject(
    myDataObject, 
    new Newtonsoft.Json.JsonSerializerSettings 
    { 
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    })
Run Code Online (Sandbox Code Playgroud)

数据按预期序列化而没有错误.

为什么不将服务配置应用于此方法?

Kir*_*kin 6

ASP.NET Core MVC有自己的JsonSerializerSettings对象,可以在这里看到; 这是你打电话时配置的内容AddJsonOptions.应用于此实例的设置不适用于您可能已取消的方法JsonConvert.为了影响这些方法,您需要设置DefaultSettings属性.例如:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
};
Run Code Online (Sandbox Code Playgroud)

你可以在Startup班上的某个地方或甚至Program班上的某个地方做到这一点.