Home > Software design >  ASP.Net Core 6 HttpGet API ==> How to bind [FromQuery] parameter to C# object data type
ASP.Net Core 6 HttpGet API ==> How to bind [FromQuery] parameter to C# object data type

Time:07-27

I'm trying to pass a value to an endpoint created with ASP.Net Core 6 API with the following details:

Controller, Action & Model

[ApiController]
[Route("api/test")]
public class TestController
{
    [HttpGet]
    public bool Get([FromQuery] Filter filter)
    {
        return true;
    }
}

public class Filter
{
    public object Equal { get; set; }
}

Request URL

https://localhost:7134/api/test?Equal=50

As you can see the Equal property is of type object.

Note
Here is a simplified version of the situation I'm facing, and the Filter model is not changeable by me.

The Question
How can I bind 50 to the Equal property of the filter object without writing a custom model binder?

CodePudding user response:

I believe the syntax you want is :

https://localhost:7134/api/test?Filter.Equal=50

CodePudding user response:

How about passing it as another parameter?

e.g. :

    [HttpGet]
    public bool Get([FromQuery] int Equal, [FromQuery] Filter filter)
    {
        if (null == filter)
        {
            filter = new Filter();
        }

        filter.Equal = Equal;

        return true;
    }
  • Related