[BUG][csharp-netcore] Nullable but required properties not respected
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
you may want to try the latest master. I seem to recall a fix for that.
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.0was released Nov 2024 after @wing328's comment above, so it seems as if this was not fixed inmasterback then
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));