C# – Bind query parameters to a model in ASP.NET Core

asp.netasp.net-coreasp.net-mvccmodel-binding

I am trying to use model binding from query parameters to an object for searching.

My search object is

[DataContract]
public class Criteria 
{
  [DataMember(Name = "first_name")]
  public string FirstName { get; set; }
}

My controller has the following action

[Route("users")]
public class UserController : Controller 
{
  [HttpGet("search")]
  public IActionResult Search([FromQuery] Criteria criteria)
  {
    ...
  }
}

When I call the endpoint as follows .../users/search?first_name=dave the criteria property on the controller action is null.
However, I can call the endpoint not as snake case .../users/search?firstName=dave and the criteria property contains the property value. In this case Model Binding has worked but not when I use snake_case.

How can I use snake_case with Model Binding?

Best Answer

You need to add [FromQuery] attribute to the model properties individually

public class Criteria
{
  [FromQuery(Name = "first_name")]
  public string FirstName { get; set; }
}