简体   繁体   中英

Setting Library Parameter Globally (Newtonsoft.Json MaxDepth)

I'm trying to upgrade a monolithic repo so that it is no longer susceptible to this NewtonsSoft.Json Exploit . I'm new to C# so maybe that's why I'm having a little trouble understanding the fix. They say

This can be done globally with he following statement:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 };

I think I could just set this in each classes constructor that relies on Newtonsoft, but that would create a whole lot of duplication (example below). Am I totally off, is there a cleaner way to do things?

using Newtonsoft.Json

private class MyClasss
{
    public MyClass()
    {
      // add this line here
      JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 };
      // other steps
    }
    // other methods
}

Notes:

  1. I'm working in a monolithic repo full of a bunch of solutions that each contain multiple projects.

  2. We can't update to Json.NET 13.0.1 because of some external dependencies.

  3. We are using.Net 3.1 and there seems to be about 5 entrypoints to our repo.

JsonConvert.DefaultSettings is a public static Func<JsonSerializerSettings> , so you only really need to set it once, on startup.

You have a few options for doing this which should be easier than setting it in every class constructor:

  1. You note that your monolithic repo has 5 entry points, so you could set JsonConvert.DefaultSettings in each Program.cs .

  2. If you have some class that is used by all consumers of your monolithic repo, you could set JsonConvert.DefaultSettings in the static constructor for that class:

     public class SomeUniversallyUsedClass { static SomeUniversallyUsedClass() { // add this line here JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 }; } // Remainder of the class }
  3. You mention you are using.NET 6 .NET Core 3.1. In c# 9.0/.NET 5 and later, you can use a module initializer to set JsonConvert.DefaultSettings once for every module in your monolithic repo like so:

     internal class JsonNetModuleInitializer { [System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { // add this line here JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 }; } }

    If you are using a version earlier than .NET 5, you could still introduce JsonNetModuleInitializer and call JsonNetModuleInitializer.Initialize() from your 5 entry points and/or the static constructors for your commonly used classes.

    Demo fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM