Skip to content

Fix EmptyBodyBehavior with empty content-type #38092

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
Nov 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
Expand Down Expand Up @@ -143,6 +144,17 @@ public async Task BindModelAsync(ModelBindingContext bindingContext)

if (formatter == null)
{
if (AllowEmptyBody)
{
var hasBody = httpContext.Features.Get<IHttpRequestBodyDetectionFeature>()?.CanHaveBody;
hasBody ??= httpContext.Request.ContentLength is not null && httpContext.Request.ContentLength == 0;
if (hasBody == false)
{
bindingContext.Result = ModelBindingResult.Success(model: null);
return;
}
}

_logger.NoInputFormatterSelected(formatterContext);

var message = Resources.FormatUnsupportedContentType(httpContext.Request.ContentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,62 @@ public async Task BindModel_PassesAllowEmptyInputOptionViaContext(bool treatEmpt
Times.Once);
}

[Fact]
public async Task BindModel_SetsModelIfAllowEmpty()
{
// Arrange
var mockInputFormatter = new Mock<IInputFormatter>();
mockInputFormatter.Setup(f => f.CanRead(It.IsAny<InputFormatterContext>()))
.Returns(false);
var inputFormatter = mockInputFormatter.Object;

var provider = new TestModelMetadataProvider();
provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

var bindingContext = GetBindingContext(
typeof(Person),
metadataProvider: provider);
bindingContext.BinderModelName = "custom";

var binder = CreateBinder(new[] { inputFormatter }, treatEmptyInputAsDefaultValueOption : true);

// Act
await binder.BindModelAsync(bindingContext);

// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.IsValid);
}

[Fact]
public async Task BindModel_FailsIfNotAllowEmpty()
{
// Arrange
var mockInputFormatter = new Mock<IInputFormatter>();
mockInputFormatter.Setup(f => f.CanRead(It.IsAny<InputFormatterContext>()))
.Returns(false);
var inputFormatter = mockInputFormatter.Object;

var provider = new TestModelMetadataProvider();
provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

var bindingContext = GetBindingContext(
typeof(Person),
metadataProvider: provider);
bindingContext.BinderModelName = "custom";

var binder = CreateBinder(new[] { inputFormatter }, treatEmptyInputAsDefaultValueOption: false);

// Act
await binder.BindModelAsync(bindingContext);

// Assert
Assert.False(bindingContext.ModelState.IsValid);
Assert.Single(bindingContext.ModelState[bindingContext.BinderModelName].Errors);
Assert.Equal("Unsupported content type ''.", bindingContext.ModelState[bindingContext.BinderModelName].Errors[0].Exception.Message);
}

// Throwing InputFormatterException
[Fact]
public async Task BindModel_CustomFormatter_ThrowingInputFormatterException_AddsErrorToModelState()
Expand Down
29 changes: 29 additions & 0 deletions src/Mvc/test/Mvc.FunctionalTests/InputFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,20 @@ public async Task BodyIsRequiredByDefault()
});
}

[Fact]
public async Task BodyIsRequiredByDefaultFailsWithEmptyBody()
{
var content = new ByteArrayContent(Array.Empty<byte>());
Assert.Null(content.Headers.ContentType);
Assert.Equal(0, content.Headers.ContentLength);

// Act
var response = await Client.PostAsync($"Home/{nameof(HomeController.DefaultBody)}", content);

// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.UnsupportedMediaType);
}

[Fact]
public async Task OptionalFromBodyWorks()
{
Expand All @@ -197,4 +211,19 @@ public async Task OptionalFromBodyWorks()
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}

[Fact]
public async Task OptionalFromBodyWorksWithEmptyRequest()
{
// Arrange
var content = new ByteArrayContent(Array.Empty<byte>());
Assert.Null(content.Headers.ContentType);
Assert.Equal(0, content.Headers.ContentLength);

// Act
var response = await Client.PostAsync($"Home/{nameof(HomeController.OptionalBody)}", content);

// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
}