ASP.NET Core 2.2: Complex Object as Parameter in a HttpGet

Is it possible to use a complex object as a parameter of an HttpGet action in ASP.NET Core? Yes, it is. We must use the FromQuery attribute. Here is an example:

[HttpGet("complex")]
public MiClase GetComplejo([FromQuery] MyClass myClass)
{
  return myClass;
}

Here, MyClass is the complex object we want to pass as a parameter to the action. Here the code of MyClass:

public class MyClass
{
  public string Property1 { get; set; }
  public int Property2 { get; set; }
}

Of course, we can place as many properties as we want in our class. Finally, to fill the properties of our complex object, we use query strings:

https://localhost:44339/api/authors/complex?property=Felipe&property2=999

With this, the properties of our object will be filled in the previous action.

Something we should keep in mind, is that the validation rules are taken into account. For example, if we place a Required attribute on one of our properties of our class, then that property must be present in the query strings of the URL, otherwise, we will get a Bad Request error.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s