dotnet / dotnet/aspnetcore

Collections of non-nullable types are not checked for null in ASP.NET Core APIs

Open
#57,234 16 comments 2 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

My ASP.NET Core 8 Web API has a controller with a POST endpoint, it accepts the following DTO:
```csharp
public class RequestDtoObject
{
public List Names { get; set; }
public string Name { get; set; }
}
```

This is set up in an action that just returns the object:
```csharp
[HttpPost]
public IActionResult EchoResponse([FromBody] RequestDtoObject requestDto)
{
return Ok(requestDto);
}
```

When `Name` or `Names` is set to null, the API returns a bad request indicating which field is null, which makes sense as these properties are non-nullable (the project has Nullable enabled). However, if I send in a null in the `Names` list, the `Names` property will contain a `null` value despite the fact it is a list of non-nullable strings. The following request object is accepted:
```json
{
"names": ["string", null],
"name": "string"
}
```

### Expected Behavior

I expect a bad request response when requests has a list of non-nullable types with a null-value in them, similar to how validation works on other non-nullable properties.

### Steps To Reproduce

https://github.com/martinmine/NotNullApi

### Exceptions (if any)

_No response_

### .NET Version

8.0.303

### Anything else?

_No response_

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.