Skip to content

Commit c0e2100

Browse files
committed
Fix RequestDelegateFactory to handle nullable types correctly in empty request body scenarios
1 parent 285f843 commit c0e2100

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/Http/Http.Extensions/src/RequestDelegateFactory.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1375,7 +1375,9 @@ private static Expression AddResponseWritingToMethodCall(Expression methodCall,
13751375
{
13761376
object? defaultBodyValue = null;
13771377

1378-
if (allowEmptyRequestBody && bodyType.IsValueType)
1378+
var isNullableType = bodyType.IsGenericType && bodyType.GetGenericTypeDefinition() == typeof(Nullable<>);
1379+
1380+
if (allowEmptyRequestBody && bodyType.IsValueType && !isNullableType) // Nullable types should be left null
13791381
{
13801382
defaultBodyValue = CreateValueType(bodyType);
13811383
}

src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -896,6 +896,27 @@ public async Task RequestDelegateRejectsEmptyBodyGivenExplicitFromBodyParameter(
896896
Assert.Equal(400, httpContext.Response.StatusCode);
897897
}
898898

899+
[Fact]
900+
public async Task RequestDelegatePopulatesNullFromBodyNullableParameterWithEmptyBody()
901+
{
902+
var httpContext = CreateHttpContext();
903+
httpContext.Request.Headers["Content-Type"] = "application/json";
904+
httpContext.Request.Headers["Content-Length"] = "0";
905+
httpContext.Features.Set<IHttpRequestBodyDetectionFeature>(new RequestBodyDetectionFeature(false));
906+
907+
var factoryResult = RequestDelegateFactory.Create(
908+
([FromBody] int? body) =>
909+
{
910+
httpContext.Items["body"] = body;
911+
}
912+
);
913+
914+
var requestDelegate = factoryResult.RequestDelegate;
915+
await requestDelegate(httpContext);
916+
917+
Assert.Null(httpContext.Items["body"]);
918+
}
919+
899920
[Fact]
900921
public void RequestDelegateFactoryThrowsForByRefReturnTypes()
901922
{

0 commit comments

Comments
 (0)