Search code examples
asp.net-web-apiasp.net-core-2.0asp.net-apicontroller

How to query bind parameter?


I'm trying to query bind the parameter id. It keeps coming through as 0. s2 has a value when supplied:

id=0, s=null
http://localhost/api/values/123

id=0, s2=true
http://localhost/api/values/123?s2=true

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet("sub/{id?}")] 
    public string Get([FromQuery]int id, string s2)
    {
        return "value";
    }

Why isn't id being captured?


Solution

  • Change your code to use FromRoute for an Id as it is coming via route and change Http Get as well, it is not aligned with what you passing in url

    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpGet()] 
        public string Get([FromRoute]int id, [FromQuery]string s2)
        {
            return "value";
        }
    }