我目前有这个控制器
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无效?我做错了什么?
答案 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);
}
}
}