Search code examples
asp.net-web-api2asp.net-web-api-routing

Web Api 2 : How to make ModelState recognize optional parameters?


I currently have this controller

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id, [FromUri]int? AnotherId ){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}

When I try to access /api/Home?id=&AnotherId=1 or /api/Home?id=1&AnotherId=, it returns the following error A value is required but was not present in the request. I have clearly indicated that id or AnotherId should be an optional value.

Why is the ModelState not valid? What am I doing wrong?


Solution

  • It seems like ModelState in Web Api doesn't recognize this kind of parameter ?a=&b=. Not exactly sure why but we need to add a [BinderType] to [FormUri] like this:

    [RoutePrefix("api/Home")]
    public class HomeController : ApiController
    {
    
        [HttpGet]
        [Route("")]
        public IHttpActionResult GetByIdAndAnotherID(
            [FromUri(BinderType = typeof(TypeConverterModelBinder))]int? ID = null,
            [FromUri(BinderType = typeof(TypeConverterModelBinder))]int? AnotherID = null){
    
            if (!ModelState.IsValid) //From ApiController.ModelState
            {
                return BadRequest(ModelState);
            }
        }
    }