Trying to pass complex object as a parameter of the HttpGet request (FromQuery)

Stas G 0 Reputation points
2024-04-04T09:13:35.4+00:00

Hi, i have standard ASP.NET application with controllers and what i try to do is to pass complex object as a parameter of the HttpGet request.

Like :

 [HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get([FromQuery]MyParam? myParam)
{
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

MyParam class looks as follows :

public class MyParam
{
    public string Name { get; set; }
    public string StringValue { get; set; }
    public int IntValue { get; set; }
}

What can be a reason that MyParam class is not added to the schema and i see it's structure flattened in the parameters section of the Get request in the Swagger?

I see 3 different parameters Name, StringValue and IntValue as a Get parameters.

If i change my class definition as follows (from properties to class members) MyParam class is added to schema and i see one parameter which is called myParam and i should provide json to populate it.

   public class MyParam
   {
       public string Name;
       public string StringValue ;
       public int IntValue ;
   }

I don't understand this behavior and i want to achieve the same result that i get with class members but with properties.

Thank you!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,564 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points
    2024-04-04T15:38:52.8933333+00:00

    the binder expects each object property to be passed as a separate query string (or form body) parameter with the proper name. in your case its:

    GetWeatherForecast?myParam.Name=foo&myParam.StringValue=foo&myParam.IntValue=42

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.