dotnet / dotnet/aspnetcore

Json parsing error behaviors control in Minimal Api

Open
#44,538 9 comments 6 reactions 1 assignee Claimed by @halter73 View on GitHub
api-suggestion area-minimal
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

## Background and Motivation

I was porting one of my API from controllers to minimal API. I noticed an unexpected behavior in minimal API. Like when I have invalid JSON in the request body in controllers the parameter binds to null and there is an error message added to `ModelStateDictionary`. But in minimal APIs, it throws a JsonException, most importantly the request doesn't even reach the handler method. I wasn't expecting that. Because in my mind minimal API suppose to give me more flexibility.

## Proposed API

There can be a simple solution. Instead of throwing a JsonException why not just provide the handler with correct error messages?

```c#
public class ParsingError
{
// necessary infors
}
public class ParsingErrorParamaterAttribute : Attribute
{
public ParsingErrorParamaterAttribute(string paramName) {}
}
```

Here `ParsingError` will contain whole contexts about the wrong request body format. So for this to happen with custom bindings there needs to be a new overload of the BindAsync method.

```c#

public class Post
{
public static ValueTask> BindAsync(HttpContext context, ParameterInfo parameter)
{
// binding code
}
}
public record BindingResult(T? Model, ParsingError? Error);
```

So now custom bindings can also return ParsingError.

## Usage Examples

The usage would be very simple. There will be just one extra parameter.
```C#
app.MapPost("api/posts/", (Post post, [ParsingErrorParamater("post")] ParsingError postParsingError) =>
{
// handler code
});
```

## Alternative Designs

There can be a configuration option to turn this on or off.

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.