Web API 2在长id参数上给出了404

时间:2014-04-12 07:11:46

标签: asp.net-web-api2

我正在使用Web API 2(使用MVC 5)从MongoDb商店访问某些数据。这是行动/方法:

    [Route("api/container/children/{parentId}")]
    [HttpGet]
    public HttpResponseMessage GetChildren(String parentId) {
        ObjectId containerId;
        if (!ObjectId.TryParse(parentId, out containerId)) {
            IEnumerable<Container> containers = this.Connection.GetCollection<Container>().FindAs<Container>(Query.EQ(Container.FieldNames.ParentId, containerId));
            return this.Request.CreateResponse<Container[]>(HttpStatusCode.OK, containers.ToArray());
        }

        return this.Request.CreateResponse(HttpStatusCode.NotFound);
    }

使用$ .get从jQuery调用方法时,在使用参数ObjectId.Empty(即000000000000000000000000)调用时让我得到404,所以调用此Url会给我一个404:

/ API /容器/儿童/ 000000000000000000000000

但是调用此网址可以正常工作:

/ API /容器/儿童/ 0000000000000000

是否对Web API 2上的(id)参数的长度有某种限制?

1 个答案:

答案 0 :(得分:0)

这不是WebAPI问题。

代码中的错误实际上非常简单。删除if条件

中的not(!)运算符
[Route("api/container/children/{parentId}")]
[HttpGet]
public HttpResponseMessage GetChildren(String parentId) {
    ObjectId containerId;
    if (ObjectId.TryParse(parentId, out containerId)) {
        ...
    }

    return this.Request.CreateResponse(HttpStatusCode.NotFound);
}