Web Api 2:如何使ModelState识别可选参数?

时间:2017-11-15 12:00:59

标签: asp.net-web-api2 asp.net-web-api-routing

我目前有这个控制器

var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];

当我尝试访问[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); } } } /api/Home?id=&AnotherId=1时,会返回以下错误/api/Home?id=1&AnotherId=我已明确指出A value is required but was not present in the request.id应该是可选的值。

为什么ModelState无效?我做错了什么?

2 个答案:

答案 0 :(得分:1)

您定义的路线是:

[Route("{id?}/{AnotherId?}")]

这意味着您可以按以下方式调用/api/Home/0/1,其中0将解析为id的值,1将解析为AnotherId的值

我相信如果删除该路由属性并保留[Route("")]路由属性,您应该可以按照预期(/api/Home?id=&AnotherId=1/api/Home?id=1&AnotherId=)调用该方法并获取你期待的结果。

答案 1 :(得分:0)

似乎Web Api中的ModelState无法识别此类参数?a=&b=。不完全确定原因,但我们需要add a [BinderType] to [FormUri]这样:

[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);
        }
    }
}