Web API 2 FromUri可选的null默认参数

时间:2016-04-19 17:11:19

标签: c# asp.net-web-api2

我有以下控制器方法:

[HttpGet]
[Route("api/users/{lookup}/{id?}")]
public async Task<IHttpActionResult> GetUsers(string lookup, [FromUri]string[] id = null) { //Can a parameter than comes FromUri ever be null?
    var repo = _uProvider.GetRepository(lookup);
    if (repo == null) {
        return Content(HttpStatusCode.NotFound, String.Concat(lookup, " is not a valid lookup type."));
    }
    if (id == null || id.Length == 0) { //added id.Length check because id was never null
        var all = await repo.GetAll();
        return Ok(all);
    }
    var users = await repo.GetUsersByIds(id);
    if (users == null) {
        return NotFound();
    }
    return Ok(users);
}

为什么当我向api / users / domain提交Get请求时,string[] id永远不会为空?我必须添加id.Length == 0检查以捕获客户端想要域内完整用户列表的用例。

1 个答案:

答案 0 :(得分:2)

我不相信它可以为null。我认为它会默认为一个空数组,因为在发送的JSON字符串中将是&#34; []&#34;。

相关问题