Skip to content

NullReferenceException in SchemaGenerator.GenerateSchemaForMember when using AddSwaggerGenNewtonsoftSupport #2528

@ozziepeeps

Description

@ozziepeeps

Hi. Getting a NullReferenceException in SchemaGenerator.GenerateSchemaForMember when using AddSwaggerGenNewtonsoftSupport. I'm using version 6.4.0 of the following packages:

    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
    <PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.4.0" />

Here are repro steps (assumes you have .NET 6 SDK installed):

  1. dotnet new webapi
  2. dotnet add package Swashbuckle.AspNetCore (updates to 6.4.0)
  3. dotnet add package Swashbuckle.AspNetCore.Newtonsoft (installs 6.4.0)
  4. Edit Program.cs to add the line builder.Services.AddSwaggerGenNewtonsoftSupport();
  5. Edit WeatherForecast.cs to add the line public Dictionary<DayOfWeek, DayOfWeek>? DayOfWeekMap { get; set; }
  6. Run the application which will launch a browser pointing to Swagger UI
  7. Observe a NullReferenceException in SchemaGenerator.GenerateSchemaForMember

The exact pre-conditions to get this bug are:

  • Need to use the AddSwaggerGenNewtonsoftSupport
  • Need to have a model that has a property with a Dictionary type where the key is an Enum

I observed that if System.Text.Json is being used instead of Newtonsoft (essentially skipping step 4 above) then the issue does not exist since JsonSerializerDataContractResolver passes null for the keys parameter to DataContract.ForDictionary:

keys: null, // STJ doesn't currently support dictionaries with enum key types
versus NewtonsoftDataContractResolver which passes the set of keys:

The Newtonsoft behavior (passing keys rather than keys being null) means that that the if branch in SchemaGenerator.CreateDictionarySchema is executed:

This results in an OpenApiSchema being created with AdditionalPropertiesAllowed set to false and AdditionalProperties left as null (the default). When control returns to SchemaGenerator.GenerateSchemaForMember this yields the NullReferenceException on line 95, since AdditionalProperties is null:

schema.AdditionalProperties.Nullable = !memberInfo.IsDictionaryValueNonNullable();

I believe the fix to be as simple as modifying line 93

if (modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof(Dictionary<,>))

to be:

if (schema.AdditionalPropertiesAllowed && modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof(Dictionary<,>))

that is adding the schema.AdditionalPropertiesAllowed conjunction.

I will submit a PR for this but wanted to create the issue first.

Thank you for building such a useful library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions