Skip to content

Commit 6a51fb7

Browse files
committed
Fix EmptyBodyBehavior with empty content-type
1 parent 5ae570d commit 6a51fb7

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,11 @@ public async Task BindModelAsync(ModelBindingContext bindingContext)
143143

144144
if (formatter == null)
145145
{
146+
if (AllowEmptyBody && httpContext.Request.ContentLength == 0)
147+
{
148+
return;
149+
}
150+
146151
_logger.NoInputFormatterSelected(formatterContext);
147152

148153
var message = Resources.FormatUnsupportedContentType(httpContext.Request.ContentType);

src/Mvc/test/Mvc.FunctionalTests/InputFormatterTests.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,20 @@ public async Task BodyIsRequiredByDefault()
188188
});
189189
}
190190

191+
[Fact]
192+
public async Task BodyIsRequiredByDefaultFailsWithEmptyBody()
193+
{
194+
var content = new ByteArrayContent(Array.Empty<byte>());
195+
Assert.Null(content.Headers.ContentType);
196+
Assert.Equal(0, content.Headers.ContentLength);
197+
198+
// Act
199+
var response = await Client.PostAsync($"Home/{nameof(HomeController.DefaultBody)}", content);
200+
201+
// Assert
202+
await response.AssertStatusCodeAsync(HttpStatusCode.UnsupportedMediaType);
203+
}
204+
191205
[Fact]
192206
public async Task OptionalFromBodyWorks()
193207
{
@@ -197,5 +211,20 @@ public async Task OptionalFromBodyWorks()
197211
// Assert
198212
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
199213
}
214+
215+
[Fact]
216+
public async Task OptionalFromBodyWorksWithEmptyRequest()
217+
{
218+
// Arrange
219+
var content = new ByteArrayContent(Array.Empty<byte>());
220+
Assert.Null(content.Headers.ContentType);
221+
Assert.Equal(0, content.Headers.ContentLength);
222+
223+
// Act
224+
var response = await Client.PostAsync($"Home/{nameof(HomeController.OptionalBody)}", content);
225+
226+
// Assert
227+
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
228+
}
200229
}
201230
}

0 commit comments

Comments
 (0)