JsonInputFormatter - Json Serialization Errors (ASP.NET Core 2.2)
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
The following [StackOverflow question](https://stackoverflow.com/questions/59877835/jsonreaderexception-unexpected-character-encountered-while-parsing-value/59883052) describes some of the detail.
I am trying to control the error messages which are returned when the `JsonSerializer` fails to deserialize the request body within the `JsonInputFormatter`, the current implementation of the input formatter forces me to override the `ReadRequestBodyAsync` method of `JsonInputFormatter` to access the `context` and add the custom error message to the `ModelStateDictionary`.
`AllowInputFormatterExceptionMessages` does not help because the application returns empty messages when set to false.
The reason for wanting to override these error messages is because they're not extremely helpful when exposing a public API, in my opinion, and having the ability to customize the error message to provide something more readable would be a better solution.
### Describe the solution you'd like
1. Add a property to `MvcJsonOptions` which allows for people to apply a templated string. `{0}` and `{1}` could be replaced with `path` and `member` from the `ReadRequestBodyAsync` method.
Example code snippet:
```csharp
public class MvcJsonOptions
{
...
public string SerializationErrorMessageTemplate { get; set; }
}
```
[line 283 of JsonInputFormatter](https://github.com/dotnet/aspnetcore/blob/30eec7d2ae99ad86cfd9fca8759bac0214de7b12/src/Mvc/Mvc.Formatters.Json/src/JsonInputFormatter.cs#L283)
```csharp
if (!string.IsNullOrWhitespace(_jsonOptions.SerializationErrorMessageTemplate))
{
var modelStateErrorMessage = string.Format(_jsonOptions.SerializationErrorMessageTemplate,
eventArgs.ErrorContext.Path,
eventArgs.ErrorContext.Member);
context.ModelState.TryAddModelError(key, modelStateErrorMessage);
} else {
var metadata = GetPathMetadata(context.Metadata, eventArgs.ErrorContext.Path);
var modelStateException = WrapExceptionForModelState(eventArgs.ErrorContext.Error);
context.ModelState.TryAddModelError(key, modelStateException, metadata);
}
```
2. Allow `WrapExceptionForModelState` to be overridden in a more derived type to reduce the.
Contributor guide
Assessment
This issue has not been assessed yet.