All rules
CA2326Security Enabled by default: No

Do not use TypeNameHandling values other than None

Do not use TypeNameHandling values other than None

Microsoft docs

Description

This rule finds Newtonsoft.Json.TypeNameHandling values other than None. If you want to deserialize only when a Newtonsoft.Json.Serialization.ISerializationBinder is specified to restrict deserialized types, disable this rule and enable rules CA2327, CA2328, CA2329, and CA2330 instead.

Cause

This rule fires when either of the following conditions are met:

  • A Newtonsoft.Json.TypeNameHandling enumeration value, other than None, is referenced.
  • An integer value representing a non-zero value is assigned to a TypeNameHandling variable.

How to fix violations

  • Use TypeNameHandling's None value, if possible.
  • Make the serialized data tamper-proof. After serialization, cryptographically sign the serialized data. Before deserialization, validate the cryptographic signature. Protect the cryptographic key from being disclosed and design for key rotations.
  • Restrict deserialized types. Implement a custom Newtonsoft.Json.Serialization.ISerializationBinder. Before deserializing with Json.NET, ensure your custom ISerializationBinder is specified in the Newtonsoft.Json.JsonSerializerSettings.SerializationBinder property. In the overridden Newtonsoft.Json.Serialization.ISerializationBinder.BindToType method, if the type is unexpected, return null or throw an exception to stop deserialization.
  • If you restrict deserialized types, you may want to disable this rule and enable rules CA2327, CA2328, CA2329, and CA2330. Rules CA2327, CA2328, CA2329, and CA2330 help to ensure that you use an ISerializationBinder when using TypeNameHandling values other than None.

Example

using Newtonsoft.Json;

public class ExampleClass
{
    public JsonSerializerSettings Settings { get; }

    public ExampleClass()
    {
        Settings = new JsonSerializerSettings();
        Settings.TypeNameHandling = TypeNameHandling.All;    // CA2326 violation.
    }
}

using Newtonsoft.Json;

public class ExampleClass
{
    public JsonSerializerSettings Settings { get; }

    public ExampleClass()
    {
        Settings = new JsonSerializerSettings();

        // The default value of Settings.TypeNameHandling is TypeNameHandling.None.
    }
}
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0