dotnet / dotnet/aspnetcore

JSON "null" request body rejected as an empty request body

Open
#40,415 13 comments 3 reactions 0 assignees View on GitHub
area-mvc enhancement help wanted
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I have an action method which accepts a posted `null` value for the body:

```
[HttpPost("acceptsNull")]
public string Upload(WeatherForecast? forecast = null)
{
return JsonConvert.SerializeObject(forecast);
}
```

However, when I post a JSON null to this endpoint I get a 400 response complaining that the body is empty.

### Expected Behavior

Since the body is not empty and JSON-deserializes to the model parameter type just fine, I expect it to invoke the action with a null model.

If it can't do that, I at least expect an error message that indicates nulls are not permitted rather than one claiming the body is empty (although if the body were actually empty instead of valid JSON I'd probably want this request to be rejected).

### Steps To Reproduce

Call the above endpoint with:

```
using var client = new HttpClient();
using var response = client.PostAsJsonAsync(".../acceptsNull", default(WeatherForecast));
Console.WriteLine(response.StatusCode); // 400
Console.WriteLine(await response.Content.ReadAsStringAsync()); // ...A non-empty request body is required....
```

### Exceptions (if any)

_No response_

### .NET Version

6.0.100

### Anything else?

The workaround I found is to set `[FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)]`, but I don't really want to have to do this because I'd like to reject empty bodies and accept non-empty bodies which are JSON null.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.