dotnet / dotnet/aspnetcore

When returning a TypedResult from a controller or minimal API endpoint the configured JsonOptions are not used

Open
#45,872 9 comments 3 reactions 1 assignee Claimed by @halter73 View on GitHub
area-minimal area-mvc investigate Needs: Design
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

When `JsonOptions` are configured either through `AddControllers().AddJsonOptions()` or `PostConfigure`, endpoints that return `IActionResult` respect this configuratrion. Endpoints that return `TypedResult` do not.

```csharp
builder.Services.PostConfigure(opt =>
opt.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull);

// this works as expected and omits null values from the response
[HttpGet("{thingId}")]
public async Task GetThing(string thingId, CancellationToken cancellationToken) =>
await handler.Handle(new GetThingRequest(thingId), cancellationToken) switch
{
{ } thing=> new JsonResult(thing),
_ => NotFound()
};

// this does not work, null values are always included
[HttpGet("{thingId}")]
public async Task, NotFound>> GetThing(string thingId, CancellationToken cancellationToken) =>
await handler.Handle(new GetThingRequest(thingId), cancellationToken) switch
{
{ } thing => TypedResults.Ok(thing ),
_ => TypedResults.NotFound()
};
```

Changing `Ok` to `JsonHttpResult` and passing the DI'd `JsonOptions` serializer settings does work correctly but this feels cumbersome and defeats the purpose of it being configured globally.

### Expected Behavior

I could see the argument that minimal APIs wouldn't use `JsonOptions` that were configured by chaining off `AddControllers` because you're not really using the MVC pipeline, but not respecting the options that are configured via PostConfigure is confusing. Having to DI another dependency into your controller or endpoint just to have `TypedResult.Json` respect what has already been configured also seems odd. I would expect it to simply use what was configured - same goes for `TypedResult.Ok` when your default serialization is JSON.

### Steps To Reproduce

_No response_

### Exceptions (if any)

_No response_

### .NET Version

7.0.101

### 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.