openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[BUG][csharp-netcore] Nullable but required properties not respected

Open hpx7 opened this issue 2 years ago • 3 comments

Bug Report Checklist

  • [ ] Have you provided a full/minimal spec to reproduce the issue?
  • [ ] Have you validated the input using an OpenAPI validator (example)?
  • [ ] Have you tested with the latest master to confirm the issue still exists?
  • [ ] Have you searched for related issues/PRs?
  • [ ] What's the actual output vs expected output?
  • [ ] [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

If I have a property that is required but nullable, the generated code throws during deserialization when the value is null.

openapi-generator version

6.5.0

OpenAPI declaration file content or url

spec:

"properties": {
	"deletedAt": {
		"type": "string",
		"format": "date-time",
		"nullable": true
	},
}
"required": [
	"deletedAt"
]
Generation Details

generated code:

// to ensure "deletedAt" is required (not null)
if (deletedAt == null)
{
    throw new ArgumentNullException("deletedAt is a required property for XXX and cannot be null");
}
Steps to reproduce
Related issues/PRs
Suggest a fix

hpx7 avatar Jun 02 '23 15:06 hpx7

you may want to try the latest master. I seem to recall a fix for that.

wing328 avatar Jun 04 '23 02:06 wing328

I just hit this with OpenAPI generator 7.10.0, generichost targeting .NET 6 (we cannot upgrade at the moment because we are required to maintain .NET 6 compatibility).

    Item:
      type: object
      description: _
      properties:
        parent:
          type: integer
          nullable: true
      required:
      - parent

If null is passed for the parent field, the following error is raised during deserialization:

System.ArgumentException: Property is required for class Item. (Parameter 'parent')

Note: 7.10.0 was released Nov 2024 after @wing328's comment above, so it seems as if this was not fixed in master back then

johnthagen avatar Nov 20 '25 17:11 johnthagen

In the generated Read function, this case block, for a required, nullable, integar field:

case "parent":

    if (utf8JsonReader.TokenType != JsonTokenType.Null)

        parent = new Option<int?>(utf8JsonReader.GetInt32());
    break;

Needed to be updated to something like:

case "project_group":

    if (utf8JsonReader.TokenType != JsonTokenType.Null)

        parent = new Option<int?>(utf8JsonReader.GetInt32());

    else

        // ADDED to fix: https://github.com/OpenAPITools/openapi-generator/issues/15735

        parent = new Option<int?>(null);

    break;

Otherwise, the property is never set properly and the check later on fires

if (!parent.IsSet)

    throw new ArgumentException("Property is required for class Item.", nameof(parent));


johnthagen avatar Nov 20 '25 17:11 johnthagen