Controller.json set Serialization.ReferenceLoopHandling

前端 未结 3 919
旧时难觅i
旧时难觅i 2020-12-06 18:53

is there a way to set Controller.Json ReferenceLoopHandling property?

It is currently causing a self referencing loop when parsing entities with navigation propertie

相关标签:
3条回答
  • 2020-12-06 19:23

    The question is from some time ago but it still can help other people.

    Try this in your ConfigureServices method of the Startup class:

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

    or

    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;
    });
    
    0 讨论(0)
  • 2020-12-06 19:27

    This worked for me with .NET Core 3.0.

    services.AddMvcCore().AddNewtonsoftJson(
        options => options.SerializerSettings.ReferenceLoopHandling =
            Newtonsoft.Json.ReferenceLoopHandling.Ignore);
    
    0 讨论(0)
  • I think that a prettier solution for this is to add JsonOptions in your ConfigureServices like:

    services.AddMvc().AddJsonOptions(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = 
                                   Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });
    
    0 讨论(0)
提交回复
热议问题