C# / .NET Compendium PLEN
.NET / C# / Web API, Blazor

Routing/Model Binding in Web API, SignalR in Blazor Server, PWA, Render Modes

Model Binding in Web API - where parameter values come from

Model binding is the mechanism that automatically fills the parameters of controller actions with data from the HTTP request - from the URL, the query string, the body, headers. ASP.NET Core has default conventions, but attributes let you control this explicitly.

[FromRoute] - from a URL segment

[HttpGet("{id}")] // api/orders/5
public async Task<ActionResult<OrderDto>> GetOrder([FromRoute] int id)
{
    // id = 5, taken from the URL segment
}

// [FromRoute] can often be omitted - EF automatically matches {id} to the parameter "id"
[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> GetOrder(int id) // works identically

[FromQuery] - from the query string

// GET api/orders/search?status=Pending&minAmount=100
[HttpGet("search")]
public async Task<ActionResult<List<OrderDto>>> Search(
    [FromQuery] string status,
    [FromQuery] decimal? minAmount)
{
    // status = "Pending", minAmount = 100
}

// You can also bind a whole object at once
public class OrderSearchParams
{
    public string Status { get; set; }
    public decimal? MinAmount { get; set; }
    public int Page { get; set; } = 1;
}

[HttpGet("search")]
public async Task<ActionResult<List<OrderDto>>> Search([FromQuery] OrderSearchParams searchParams)
{
    // GET api/orders/search?status=Pending&minAmount=100&page=2
    // ASP.NET Core automatycznie mapuje query params na property obiektu
}

[FromBody] - from the request body (JSON)

[HttpPost]
public async Task<ActionResult<OrderDto>> CreateOrder([FromBody] CreateOrderRequest request)
{
    // request zdeserializowany z JSON w body POST-a
}

// [FromBody] IS required for complex types in POST/PUT - without it
// the framework would by default try to read simple types from the query string,
// but for a complex object it looks in the body by default anyway (in an [ApiController])

An important rule: a method can have only one [FromBody] parameter - the request body is one stream, you can't "split" it into two separate objects.

[FromHeader] - from an HTTP header

[HttpGet]
public async Task<ActionResult> GetData([FromHeader(Name = "X-Correlation-Id")] string correlationId)
{
    // the value of the X-Correlation-Id header
}

[FromServices] - injecting a dependency directly into a method (Method Injection from the earlier conversation!)

[HttpPost]
public async Task<ActionResult> CreateOrder(
    CreateOrderRequest request,
    [FromServices] IEmailService emailService) // injected ONLY for this method, not in the constructor
{
    await emailService.SendAsync(...);
}

This is exactly the Method Injection I mentioned with the ways of applying DI - useful when a dependency is needed in only one specific controller action and you don't want to hold it as a field of the whole class.

Default conventions (when there is no attribute) in an [ApiController]

Parameter type Default source
A simple type (int, string, Guid) not in the route Query string
A complex object (a class) Body (JSON)
A parameter whose name matches a {segment} in the route Route

That is why int id in GetOrder(int id) with [HttpGet("{id}")] works without an explicit [FromRoute] - the parameter name matches the placeholder in the route.

Model validation - automatic thanks to [ApiController]

public class CreateOrderRequest
{
    [Required]
    [StringLength(100)]
    public string CustomerName { get; set; }

    [Range(0.01, double.MaxValue)]
    public decimal TotalAmount { get; set; }
}

[HttpPost]
public async Task<ActionResult> CreateOrder(CreateOrderRequest request)
{
    // [ApiController] ITSELF checks ModelState.IsValid BEFORE entering this method
    // if validation fails - an automatic 400 Bad Request, this code won't even run
    var order = await _orderService.CreateOrderAsync(request);
    return Ok(order);
}

Without [ApiController] you would have to check if (!ModelState.IsValid) return BadRequest(ModelState); manually in every action.

Is [FromBody] required?

The short answer: No, if the controller has the [ApiController] attribute

[ApiController] automatically infers [FromBody] for complex types, so in practice in Web API you almost never have to write it explicitly.

A demonstration - works identically with and without the attribute

[ApiController] // ← to jest kluczowe
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    // Z jawnym [FromBody]
    [HttpPost]
    public async Task<ActionResult<OrderDto>> CreateOrder([FromBody] CreateOrderRequest request)
    {
        // ...
    }

    // WITHOUT [FromBody] - works EXACTLY the same thanks to [ApiController]
    [HttpPost]
    public async Task<ActionResult<OrderDto>> CreateOrder(CreateOrderRequest request)
    {
        // ...
    }
}

[ApiController] applies the rule: a complex type (class/record) that doesn't match any route segment → bound from the body by default.

When there is NO [ApiController] and [FromBody] is actually required

[Route("api/[controller]")]
public class OrdersController : Controller // ⚠️ an ordinary Controller, WITHOUT [ApiController]
{
    [HttpPost]
    public async Task<ActionResult> CreateOrder(CreateOrderRequest request)
    {
        // ❌ WITHOUT [FromBody] - the request will be EMPTY (or have default values)!
        // Without [ApiController] the framework by default tries to bind complex types
        // from form-data, NOT from the JSON body, unless you say otherwise explicitly
    }

    [HttpPost]
    public async Task<ActionResult> CreateOrder([FromBody] CreateOrderRequest request)
    {
        // ✅ Poprawnie - jawnie wymuszasz bindowanie z JSON body
    }
}

This mainly concerns older MVC controllers (the ones rendering views, inheriting from Controller, not from ControllerBase with [ApiController]) - there [FromBody] is necessary, because without it the framework doesn't know you mean JSON from the body rather than, say, form data.

Why it is still WORTH writing [FromBody] explicitly

Even though it is technically redundant in an [ApiController], many teams (and style guidelines) recommend explicit attributes anyway:

1. Readability / self-documenting code

// Without attributes - you have to REMEMBER the conventions to know where each thing comes from
public async Task<ActionResult> Search(string status, int page, CreateOrderRequest request)

// With attributes - visible AT ONCE, just by looking at the signature
public async Task<ActionResult> Search(
    [FromQuery] string status,
    [FromQuery] int page,
    [FromBody] CreateOrderRequest request)

2. Safety during refactoring - if someone one day removes [ApiController] from the class (e.g. when migrating/merging controllers), code with explicit attributes keeps working correctly; code relying on the default conventions will silently break.

3. Unambiguity with many complex-type parameters - if a method has both a route parameter and a query one, plus something complex, being explicit removes ambiguity for others reading the code.

A practical recommendation

In new code with [ApiController] - [FromBody] is optional for POST/PUT with a single complex parameter, but many developers (and some team code style guides) add it anyway for readability.

A trick question they may ask in an interview

"What happens if you remove [FromBody] from a controller WITHOUT [ApiController]?" - the answer: the request will be bound incorrectly (the framework will try to read from form-data/query instead of JSON), which in practice means that all the object's properties will have default values (null, 0, false) - one of the classic, hard-to-diagnose bugs for people migrating from older MVC or omitting [ApiController] "by accident".

Buy me a coffee