Skip to content

Fix InvalidCastException for nullable enum parameter default values i… - #69918

Open
AnsElgyarDev wants to merge 1 commit into
dotnet:mainfrom
AnsElgyarDev:fix-openapi-nullable-enum-default
Open

AnsElgyarDev wants to merge 1 commit into
dotnet:mainfrom
AnsElgyarDev:fix-openapi-nullable-enum-default

Conversation

@AnsElgyarDev

Copy link
Copy Markdown

Fixes #69864

Description

ParameterInfo.DefaultValue returns the underlying integral value (a boxed Int32) for Nullable<TEnum> parameters rather than a TEnum. ApplyParameterInfo passed that value to ApplyDefaultValue, which serialized it using the JsonTypeInfo for TEnum?, causing an InvalidCastException during OpenAPI document generation.

This converts the default value with Enum.ToObject before applying it, matching what ParameterDefaultValue.TryGetDefaultValue and RequestDelegateFactory already do for nullable enums.

Tests

  • Added Status? = Status.Pending, TaskStatus? = TaskStatus.Canceled and Status? = null cases to RouteParametersWithDefaultValues.
  • Added a test for a [FromBody] nullable enum parameter with a default value.
  • Without the fix, the first two query cases and the body test fail with the InvalidCastException from the issue. With the fix, all Microsoft.AspNetCore.OpenApi.Tests pass.

MVC actions go through the same ApplyParameterInfo code path, but I did not add a dedicated MVC test.

@github-actions github-actions Bot added the area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc label Oct 18, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 18, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @AnsElgyarDev. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@AnsElgyarDev

Copy link
Copy Markdown
Author

The only failing check is "Local development validation / Test: Windows local development validation / Build (No NodeJS)". The log shows RZ1021 errors in src/Components/test/testassets/Components.TestServer Razor files, which are unrelated to this change (it only touches Microsoft.AspNetCore.OpenApi and its tests). All Microsoft.AspNetCore.OpenApi.Tests pass locally. Could a maintainer re-run it if needed? Thanks!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OpenAPI: nullable enum parameter with a default value throws InvalidCastException

1 participant