Skip to content

Treating empty string in form post as null for nullable value types #52499

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 12, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Treating empty string in form post as null for nullable value types
  • Loading branch information
nvmkpk authored and Praveen Potturu committed Aug 20, 2024
commit 0c61023a7a86f80433134393c72f8538d540910e
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ public bool CanConvertSingleValue() => _nonNullableConverter is ISingleValueConv

public bool TryConvertValue(ref FormDataReader reader, string value, out T? result)
{
if (string.IsNullOrEmpty(value))
{
// Form post sends empty string for a form field that does not have a value,
// in case of nullable value types, that should be treated as null and
// should not be parsed for its underlying type
result = null;
return true;
}

var converter = (ISingleValueConverter<T>)_nonNullableConverter;

if (converter.TryConvertValue(ref reader, value, out var converted))
Expand All @@ -30,17 +39,20 @@ public bool TryConvertValue(ref FormDataReader reader, string value, out T? resu

[RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)]
[RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)]
internal override bool TryRead(ref FormDataReader context, Type type, FormDataMapperOptions options, out T? result, out bool found)
internal override bool TryRead(ref FormDataReader reader, Type type, FormDataMapperOptions options, out T? result, out bool found)
{
if (!(_nonNullableConverter.TryRead(ref context, type, options, out var innerResult, out found) && found))
// Donot call non-nullable converter's TryRead method, it will fail to parse empty
// string. Call the TryConvertValue method above (similar to ParsableConverter) so
// that it can handle the empty string correctly
found = reader.TryGetValue(out var value);
if (!found)
{
result = null;
return false;
result = default;
return true;
}
else
{
result = innerResult;
return true;
return TryConvertValue(ref reader, value!, out result!);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using a null suppression here, perhaps we should add [NotNullWhen] annotations to the FormDataReader.TryGetValue method.

}
}
}