Request Bodies & JSON
Clients send data to create or update resources in the request body, almost always as JSON. ASP.NET Core reads the body and deserializes it into a C# object with System.Text.Json, so your handler receives a ready-to-use typed value.
Binding the body
In minimal APIs, a parameter of a complex type (a class or record that isn't a special framework type and has no TryParse) is read from the JSON body automatically:
app.MapPost("/products", (CreateProduct input) =>
{
var product = new Product(Random.Shared.Next(100, 999), input.Name, input.Price);
return Results.Created(quot;/products/{product.Id}", product);
});
record CreateProduct(string Name, decimal Price);
record Product(int Id, string Name, decimal Price);$ curl -s -X POST localhost:5000/products -H "Content-Type: application/json" -d '{"name":"Desk lamp","price":39.90}'{"id":512,"name":"Desk lamp","price":39.90}
Rules worth knowing:
| Situation | Result |
|---|---|
Valid JSON, Content-Type: application/json |
Handler runs with the deserialized object |
| JSON is malformed or has the wrong types | 400 Bad Request |
| Body is empty for a required parameter | 400 Bad Request |
Content type isn't JSON (e.g. text/plain) |
415 Unsupported Media Type |
| More than one body parameter | Startup error — an endpoint can bind only one body |
Property names are matched case-insensitively and default to camelCase on output, thanks to the web defaults.
Note: In .NET 9, minimal APIs only check that the JSON can be deserialized. They do not run Data Annotations such as
[Required]or[Range]automatically (controllers do). The Model Binding & Validation lesson shows how to validate input yourself.
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:5000/products -H "Content-Type: application/json" -d '{"name":"Lamp","price":"cheap"}'
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:5000/products -H "Content-Type: text/plain" -d 'Lamp'400
415
Deserialization in plain C#
Everything above is ordinary System.Text.Json. Here is the same deserialization, including what happens with bad input:
using System;
using System.Text.Json;
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var ok = JsonSerializer.Deserialize<CreateProduct>("""{"NAME":"Desk lamp","price":39.90}""", web)!;
Console.WriteLine(quot;{ok.Name} costs {ok.Price}");
// Unknown properties are ignored by default
var extra = JsonSerializer.Deserialize<CreateProduct>("""{"name":"Mug","price":8,"color":"blue"}""", web)!;
Console.WriteLine(extra);
// Wrong type -> JsonException, which ASP.NET Core turns into 400 Bad Request
try
{
JsonSerializer.Deserialize<CreateProduct>("""{"name":"Lamp","price":"cheap"}""", web);
}
catch (JsonException ex)
{
Console.WriteLine(quot;JsonException at {ex.Path}");
}
record CreateProduct(string Name, decimal Price);Desk lamp costs 39.90
CreateProduct { Name = Mug, Price = 8 }
JsonException at $.price
Tip: Records with positional parameters are perfect request types (DTOs — data transfer objects): short, immutable and deserializable through their constructor.
Customizing JSON
Use attributes on the type for local changes:
| Attribute | Effect |
|---|---|
[JsonPropertyName("unit_price")] |
Use a different JSON name |
[JsonIgnore] |
Never read or write this property |
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] |
Omit when null |
[JsonConverter(typeof(JsonStringEnumConverter))] |
Enum as text instead of a number |
[JsonRequired] / required keyword |
Fail deserialization if the property is missing |
Or change the options for the whole app:
using System.Text.Json.Serialization;
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});Note:
ConfigureHttpJsonOptionsaffects minimal APIs. Controllers use their own setting:builder.Services.AddControllers().AddJsonOptions(o => …).
The same options in a runnable program:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
options.Converters.Add(new JsonStringEnumConverter());
var order = new Order(7, Status.Shipped, 120.5m, Note: null, InternalCode: "X-99");
Console.WriteLine(JsonSerializer.Serialize(order, options));
var back = JsonSerializer.Deserialize<Order>("""{"id":8,"status":"pending","unit_price":10}""", options)!;
Console.WriteLine(quot;{back.Id} {back.Status} {back.UnitPrice}");
enum Status { Pending, Shipped, Delivered }
record Order(
int Id,
Status Status,
[property: JsonPropertyName("unit_price")] decimal UnitPrice,
string? Note,
[property: JsonIgnore] string? InternalCode = null);{"id":7,"status":"Shipped","unit_price":120.5}
8 Pending 10
[property: …] applies the attribute to the generated property of a positional record. Enum names are matched case-insensitively when reading ("pending" → Pending).
Don't bind your database entities
Accepting the same class you store in the database invites over-posting: a client could send "isAdmin": true or "id": 1 and overwrite fields it should never touch. Bind a small input record and copy the allowed fields:
app.MapPut("/users/{id:int}", async (int id, UpdateProfile input, AppDb db) =>
{
var user = await db.Users.FindAsync(id);
if (user is null) return Results.NotFound();
user.DisplayName = input.DisplayName; // only what the client may change
user.Bio = input.Bio;
await db.SaveChangesAsync();
return Results.NoContent();
});
record UpdateProfile(string DisplayName, string? Bio);Other body formats
| You need | Use |
|---|---|
| HTML form fields | [FromForm] string name or [FromForm] MyForm form |
| File uploads | IFormFile file / IFormFileCollection files |
| The raw body | HttpRequest request → request.Body (a Stream) or await request.ReadFromJsonAsync<T>() |
app.MapPost("/upload", async (IFormFile file) =>
{
await using var target = File.Create(Path.Combine("uploads", Path.GetRandomFileName()));
await file.CopyToAsync(target);
return new { file.FileName, file.Length };
}).DisableAntiforgery();Form-bound minimal API endpoints validate an antiforgery token whenever the antiforgery middleware is active (as in Razor and Blazor apps). For a pure API called by other programs, DisableAntiforgery() turns that check off.
Test yourself
A POST handler has the parameter CreateProduct input (a record). Where does ASP.NET Core read it from?
- The query string
- The route
- The JSON request body
- A header named
input
The client sends {"price":"cheap"} where Price is a decimal. What status does the API return?
- 200 with price 0
- 400 Bad Request
- 415 Unsupported Media Type
- 500 Internal Server Error
How do you make all minimal API responses write enums as strings?
- Add
[Serializable]to each enum builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()))- Return
enum.ToString()everywhere - Set
"Enums": "String"in appsettings.json