.Net Core Model Binders

Norbert Dębosz
2 min readMar 29, 2021

ASP .Net core shares a couple of attributes that explicitly choose a model binder to bind data from the request into our action.

Here is a list of them:

  • [FromQuery] — parameter will be bound from the query params example: www.mywebside.com/test?myParam=2
  • [FromBody] — the parameter will be bound from the request body.
  • [FromRoute] — parameter will be bound from the route. www.mywebsite.com/product/765/info
  • [FromForm] — for content type multipart/form-data.
  • [FromHeader] — from a request header.

The first step is to add an [ApiController] attribute above a Controller.[ApiController] attribute will enable default behaviours (as model binders) for all our controller’s actions. It is available from .Net Core 2.1.

Default model binders bound parameters based on some simple logic:
This logic is consistent with a RESTful approach to an API.

  • If a parameter is a complex type, e.g Class — [FromBody]
  • If a parameter is a primitive type, e.g “string” -[FromQuery]
  • If a parameter fits a parameter name in a route — [FromRoute]
  • If a parameter is IFormFile — [FromForm]

The HTTP verb used to decorate action is not relevant and not used in choosing a Model Binder.

So if the [ApiController] attribute works so well, why we even should care about the above attributes?

The reason why is that sometimes we have to explicitly choose/change the default behaviour of our API controllers.

Most common usage:

GET— many query params in request and you want to pass it as a complex type (e.g pagination/ordering/filtering)

Summary:

  • From .Net Core 2.1, we can decorate a controller by the [ApiController] attribute.
  • [ApiController] attribute will choose a default model binder for us base on a RESTful API style logic.
  • There are situations that we want to explicitly choose a model binder — e.g. pagination/sorting/filtering.

Have you ever had to choose a model binder explicitly? If yes, then when?

--

--

Norbert Dębosz

Solution Architect | Tech Lead | .Net Developer who searches for the perfect balance between business values and code quality.