基于 WebAPI2 属性的路由 404 嵌套路由

WebAPI2 attribute based routing 404 with nested route

我知道有很多(已回答)与基于属性的路由相关的问题,但我似乎找不到能回答我的特定情况的问题。

我有一个 WebAPI 2 控制器,有一些使用默认路由的方法:

public Dictionary<int, SensorModel> Get()
{
    return SensorModel.List();
}

public SensorModel Get(int id)
{
    return SensorModel.Get(id);
}

[HttpPost]
public SensorModel Post(SensorModel model)
{
    if (model == null) throw new Exception("model cannot be null");
    if (model.Id <= 0) throw new Exception("Id must be set");
    return SensorModel.Update(model.Id, model);
}

这些都很好。我正在尝试创建一个嵌套路由,如下所示:

[Route("sensor/{id}/suspend")]
public SensorModel Suspend(int id, DateTime restartAt, EnSite site)
{
    return SensorModel.Suspend(id, restartAt, site);
} 

为此,我希望 URL 看起来像:

http://[application_root]/api/sensor/1/suspend?restartAt={someDateTime}&site={anInt}

抱歉,忘了说实际问题是 404! 谁能告诉我我做错了什么?我知道我可以这样做:

[Route("sensor/suspend")]
public SensorModel Suspend(int id, DateTime restartAt, EnSite site)
{
    return SensorModel.Suspend(id, restartAt, site);
}

这使得 URL:

http://[application_root]/api/sensor/suspend?id=1&restartAt={someDateTime}&site={anInt}

但我认为更简洁的 API 设计似乎是嵌套路由。

这一点你的假设是错误的:

For which I would expect the URL to look like:

http://[application_root]/api/sensor/1/suspend?restartAt={someDateTime}&site={anInt}

应该如下所示:

http://[application_root]/sensor/1/suspend?id=1&restartAt={someDateTime}&site={anInt}

当您指定基于属性的路由时,它会覆盖 ../api/.. 的默认路由架构(或您在 route.config 文件中指定的任何内容)。

因此,每当您尝试使用 基于属性的路由 时,您应该执行类似 /route_prefix_at_controller_level/route_prefix_at_method_level.

的操作