简体   繁体   中英

Web API 2 FromUri optional null default parameters

I have the following controller method:

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

Why is it that when I submit a Get request to api/users/domain, the string[] id is never null? I had to add the id.Length == 0 check to catch the use case where a client would like a full list of users within the domain.

I do not believe that it can be null. I think that it would default to an empty array, as in the JSON string sent would be as "[]".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM