dotnet / dotnet/aspnetcore

ModelState.AddModelError problemdetails resulting object doesn't match that of model validation

Open
#17,856 8 comments 7 reactions 0 assignees View on GitHub
affected-very-few area-mvc bug feature-model-binding investigate severity-minor
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

Given a fairly simple mvc action such as:

```csharp
[ApiController]
public class MyController : ControllerBase
{
[HttpPost]
public IActionResult Foo([FromBody] Command request)
{
ModelState.AddModelError(a => a.Bar, "Invalid.");
return ValidationProblem();
}
}
public class Command
{
[BindProperty(Name = "bar")]
[BindRequired]
[Required]
public string Bar { get; set; }
}
```

Submitting a post to the action which would trigger a model validation error, such as posting:

```json
{
"bar": ""
}
```

presents a ProblemDetails response:

```json
{
"errors": {
"bar": [
"The Bar field is required."
]
},
...
}
```

But any validations which do not flow through the built in validation framework are unable to utilize the logic for naming the error properties. They instead result in:

```json
{
"errors": {
"Bar": [
"Invalid."
]
},
...
}
```

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.