skip to content

In ASP.NET Core 10, why does ConfigureHttpJsonOptions leave controller responses unchanged, and how do you configure JSON for both controllers and Minimal APIs?

level: middleimportance: must knowfreq 48%

answer

  1. two classes, both named JsonOptions
  2. Microsoft.AspNetCore.Mvc.JsonOptions for formatters
  3. Microsoft.AspNetCore.Http.Json.JsonOptions for Minimal APIs
  4. AddJsonOptions vs ConfigureHttpJsonOptions
  5. MaxDepth 32 only on the MVC side

basics

~10 s

Controllers and Minimal APIs read two different option types that are both named JsonOptions. AddJsonOptions configures MVC's formatters; ConfigureHttpJsonOptions configures Minimal APIs and the request/response JSON helpers. An app with both needs both calls.

solid answer

~40 s

MVC's input and output formatters read `Microsoft.AspNetCore.Mvc.JsonOptions`, configured with `AddControllers().AddJsonOptions(...)` and exposed as `JsonSerializerOptions`. Minimal APIs, `Results`/`TypedResults` and `ReadFromJsonAsync`/`WriteAsJsonAsync` read `Microsoft.AspNetCore.Http.Json.JsonOptions`, configured with `builder.Services.ConfigureHttpJsonOptions(...)` and exposed as `SerializerOptions`. Neither call touches the other type, so an app that mixes controllers and Minimal API endpoints must configure both, typically through one shared helper that adds the same converters and policies. The two also differ in defaults: the MVC type caps `MaxDepth` at 32 and has `AllowInputFormatterExceptionMessages`, while the Minimal API type uses the relaxed JSON escaping encoder. A frequent bug is `Configure<JsonOptions>` with the wrong `using`, which silently configures the stack you are not using.

code

csharp · 24 lines
csharp
using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

static void ConfigureJson(JsonSerializerOptions o)
{
    o.Converters.Add(new JsonStringEnumConverter());
    o.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
}

// MVC formatters read Microsoft.AspNetCore.Mvc.JsonOptions
builder.Services.AddControllers()
    .AddJsonOptions(o => ConfigureJson(o.JsonSerializerOptions));

// Minimal APIs read Microsoft.AspNetCore.Http.Json.JsonOptions
builder.Services.ConfigureHttpJsonOptions(o => ConfigureJson(o.SerializerOptions));

var app = builder.Build();
app.MapControllers();
app.MapPost("/webhooks/carrier", (CarrierEvent e) => TypedResults.NoContent());
app.Run();

record CarrierEvent(string TrackingNumber, string Status);

go deeper

for a junior

Remember that AddJsonOptions is for controllers and ConfigureHttpJsonOptions is for Minimal APIs, and that a mixed app needs both.

for a middle

Explain the two JsonOptions types, their namespaces and property names, which components read each, and the using-directive trap with Configure<JsonOptions>.

for a senior

Keep one JSON contract across both stacks with a shared helper, and know the default differences (MaxDepth, exception messages, escaping) that surface in production.

for a principal

Make the JSON contract a shared, reviewed component so services that mix controllers and Minimal APIs cannot drift apart silently.

## Two option types with one name ASP.NET Core 10 has **two** classes called `JsonOptions`, and that naming collision is the whole story behind this question. | | MVC (controllers, Razor Pages) | Minimal APIs and HTTP JSON helpers | |---|---|---| | Type | `Microsoft.AspNetCore.Mvc.JsonOptions` | `Microsoft.AspNetCore.Http.Json.JsonOptions` | | Configure with | `AddControllers().AddJsonOptions(o => ...)` | `builder.Services.ConfigureHttpJsonOptions(o => ...)` | | Serializer options property | `JsonSerializerOptions` | `SerializerOptions` | | Read by | `SystemTextJsonInputFormatter`, `SystemTextJsonOutputFormatter`, `JsonResult` | Minimal API parameter binding, `Results.Ok`, `TypedResults.Ok`, `ReadFromJsonAsync`, `WriteAsJsonAsync` | | Starts from | `JsonSerializerDefaults.Web` | `JsonSerializerDefaults.Web` | | Extra defaults | `MaxDepth = 32`; `AllowInputFormatterExceptionMessages = true` | `Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping` | Both are ordinary options classes: each extension method is a shortcut for `services.Configure<ThatJsonOptions>(...)`. ## Why one call does not reach the other stack MVC never looks at the Minimal API options type, and the Minimal API result types never look at MVC's. So in a shipping-label service where `LabelsController` serves the main API and a few Minimal API endpoints serve carrier webhooks: - `ConfigureHttpJsonOptions` adding `JsonStringEnumConverter` makes the webhooks write `"format": "Zpl"`, while the controller still writes `"format": 1`. - `AddJsonOptions` alone does the opposite. Neither is a bug; each stack honours its own type. ## Configuring both from one place The clean pattern is a single method that configures a `JsonSerializerOptions` instance, called from both registrations: ```csharp static void ConfigureJson(JsonSerializerOptions o) { o.Converters.Add(new JsonStringEnumConverter()); o.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; } builder.Services.AddControllers() .AddJsonOptions(o => ConfigureJson(o.JsonSerializerOptions)); builder.Services.ConfigureHttpJsonOptions(o => ConfigureJson(o.SerializerOptions)); ``` This keeps one contract for every endpoint and makes a code review spot a change that touches only one side. ## The using-directive trap Because the names collide, this line compiles against whichever namespace is imported: ```csharp builder.Services.Configure<JsonOptions>(o => /* ... */); ``` 1. With `using Microsoft.AspNetCore.Mvc;` it configures controllers only. 2. With `using Microsoft.AspNetCore.Http.Json;` it configures Minimal APIs only. 3. With both imported it does not compile until you qualify the name. The Web SDK's implicit usings import `Microsoft.AspNetCore.Http` but not either `JsonOptions` namespace, so one of them is always added by hand, and that is where the wrong one sneaks in. Prefer the two named extension methods: they cannot be confused. ## Differences that show up in production - **Depth:** MVC formatters stop at 32 levels; Minimal APIs use System.Text.Json's own limit. A deeply nested payload can bind in a Minimal API and fail in a controller. - **Error detail:** with `AllowInputFormatterExceptionMessages = true` (the default), MVC puts the serializer's message, such as the path of a bad token, into `ModelState`, and therefore into the 400 body. Set it to `false` when you do not want those messages sent to clients. - **Escaping:** the Minimal API options use the relaxed encoder, so HTML-sensitive characters such as `<` and `&` and non-ASCII letters are written as-is; MVC's options keep the serializer's default encoder, which escapes them. - **Per-response override:** controllers can pass options to `new JsonResult(value, options)`; Minimal APIs can pass them to `Results.Json(value, options)`. ## Diagnosing which options wrote a response When one endpoint's JSON differs from the rest, ask what produced the body: 1. An `ObjectResult` (returning a model, `Ok(model)`, `CreatedAtAction(...)`) from a controller goes through **MVC's output formatters**, so `AddJsonOptions` applies. 2. An `IResult` (`Results.Ok`, `TypedResults.Ok`, a value returned from a Minimal API lambda) goes through the **HTTP JSON helpers**, so `ConfigureHttpJsonOptions` applies, even if a controller action returned it. 3. A middleware or exception handler calling `WriteAsJsonAsync` also uses the HTTP options. That rule explains most "one endpoint has PascalCase" bug reports in mixed apps. The fix is not to pick a winner but to make both option types identical, which the shared helper does. ## Testing the contract An integration test that calls one controller route and one Minimal API route and compares the serialized shape of the same DTO catches drift early. It is cheap, and it fails the moment someone adds a converter to only one side. ## Where this sits What each `JsonSerializerOptions` property means is System.Text.Json's own API. Source-generated contexts for Native AOT are added through the same two option types, but that is an AOT concern. This question is about the plumbing: which option type each stack reads and how to keep them aligned.

  • Which JsonOptions does TypedResults.Ok use when it runs inside a controller action?
    The Minimal API type, `Microsoft.AspNetCore.Http.Json.JsonOptions`. `TypedResults` results implement `IResult` and write through the HTTP JSON helpers, not through MVC's output formatters, so `AddJsonOptions` settings do not apply to them even when a controller returns one.
  • Why might you set AllowInputFormatterExceptionMessages to false on MVC's JsonOptions?
    It defaults to `true`, so the System.Text.Json exception message for a malformed body, including paths and type details, lands in `ModelState` and from there in the 400 response. Setting it to `false` replaces those messages with a generic one, which keeps internal type names out of responses to untrusted clients.

Two thermostats of the same model in two rooms: turning one up warms only the room it is wired to. AddJsonOptions is wired to the controllers' room and ConfigureHttpJsonOptions to the Minimal API room, so a mixed house needs both set.

  • AddJsonOptions configures JSON for Minimal API endpoints as well as controllers.
  • ConfigureHttpJsonOptions is the newer name for AddJsonOptions and replaces it.
  • There is only one JsonOptions class, shared by every part of ASP.NET Core.
  • MVC and Minimal APIs enforce the same 32-level MaxDepth by default.
  • Configure<JsonOptions> always targets controllers, whatever namespace is imported.