dotnet / dotnet/aspnetcore

Model binding failure should return friendlier message with option to customize it

Open
#12,472 11 comments 8 reactions 0 assignees View on GitHub
affected-few area-mvc enhancement External feature-model-binding severity-minor
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Description
Model binding fails due to try parse whitespaced string to decimal property and exposing sensitive info to client.

### To Reproduce
Steps to reproduce the behavior:
1. I have very simple ApiController:
```
[ApiController]
public class ProductsController
{
[HttpPost]
public IActionResult Post([FromBody]CreateProductDto model)
{
model.Id = await service.CreateProduct(model);

return CreatedAtRoute(
routeName: "GetProduct",
routeValues: new { id = model.Id },
value: model
);
}
}
```

2. And model:

```
public class CreateProductDto
{
[Required(ErrorMessage = "Invalid value")]
public decimal totalPrice { get; set;}

public int count { get; set; }
}
```

3. And posting json:
` {
"totalPrice": " ",
"count": " "
}`

4. And the following model state error is returned:
`totalPrice: ["Could not convert string to decimal: . Path 'totalPrice', line 1, position 71."]
0: "Could not convert string to decimal: . Path 'totalPrice', line 1, position 71."`

### Expected behavior
Expected more user friendly message which can be exposed to api client when validating input.

### Tried possible solutions
1. To make model fields strings and then parse and validate them. (not cool solution)
2. To use Mvc Options.ModelBindingMessageProvider if applicable, but doesn't for that specific case. Would be pretty cool if can.
3. To use IValidatableObject - as the binding fails before constructing the model, this is not possible.
4. Using Validatation Attribute - same as above. Model binding fails before that.

### Additional info

```
NET Core SDK (reflecting any global.json):
Version: 2.1.701
Commit: 8cf7278aa1

Runtime Environment:
OS Name: fedora
OS Version: 30
OS Platform: Linux
RID: fedora.30-x64
Base Path: /usr/share/dotnet/sdk/2.1.701/

Host (useful for support):
Version: 2.1.12
Commit: ccea2e606d

.NET Core SDKs installed:
2.1.701 [/usr/share/dotnet/sdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.12 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.12 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.12 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

```

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.