Web API: 在路由集合中找不到名为 'X' 的路由

Web API: A route named 'X' could not be found in the route collection

关于这个错误,我已经尝试了在 Whosebug 和互联网其他地方找到的所有解决方案,但我们仍然遇到问题。

所以我们有 .NET API,它有一个 POST 方法,然后 returns 一个 CreatedAtRoute 响应 (201)。问题是当返回 CreatedAtRoute 响应时,我们收到错误 "A route named 'X' could not be found in the route collection.",其中 X 是我们的路由名称。

Global.asax

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    GlobalConfiguration.Configuration.UseStructureMap<MasterRegistry>();

    var allDirectRoutes = WebApiConfig.GlobalObservableDirectRouteProvider.DirectRoutes;
}

WebApi.config - 我们在默认路由之前声明了 MapHttpAttributes。

public static class WebApiConfig
{
    public static ObservableDirectRouteProvider GlobalObservableDirectRouteProvider = new ObservableDirectRouteProvider();

    public static void Register(HttpConfiguration config)
    {
        config.Formatters.Clear();
        config.Formatters.Add(new JsonMediaTypeFormatter());

        // Web API routes

        config.MapHttpAttributeRoutes(GlobalObservableDirectRouteProvider);

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/v1/{controller}/{id}",
            new { id = RouteParameter.Optional }
        );
    }
}

控制器 - GetCompoundById 路由 这是我们要使用命名路由

构建的路由
[HttpGet]
[Route("{id:Guid}", Name = "GetCompoundById")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(CompoundViewModel))]
public async Task<IHttpActionResult> Get(Guid id)
{
    var serviceResult = await Task.FromResult(CompoundService.Get(id));

    if (serviceResult == null)
    {
        return NotFound();
    }

    CompoundViewModel result =
            new CompoundViewModel {Id = serviceResult.Id, Name = serviceResult.Name};

    return Ok(result);
}

控制器 - Return CreatedAtRoute 在 POST 动作中 这是抛出错误的地方,因为找不到指定的路由。

return CreatedAtRoute("GetCompoundById", new {id = result.Id}, result);

注意:在 WebApi.config 中,我创建了一个 ObservableDirectRouteProvider,它允许我查看启动时创建的路由,并且我可以看到我的命名路由存在于集合中。

如果我们在控制器中使用路由前缀,我们应该为所有操作定义路由名称。使用这个

[HttpGet]
[Route(Name = "GetCompounds")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<ApiModels.CompoundViewModel>))]
public async Task<IHttpActionResult> Get(int page = 0,int pageSize = CoreModels.Pagination.DefaultPageSize)

奇怪的是,这个问题与我们使用命名路由或配置 WebAPI 路由的方式没有直接关系(这解释了为什么所有其他帖子都没有帮助我修复它)。我们发现这个问题是我们如何使用 StructureMap 作为我们的 IoC 容器的副作用。

在我们调用的 StructureMap 注册表中

scanner.SingleImplementationsOfInterface();

这有导致错误的奇怪副作用。通过执行一个非常漫长而乏味的消除过程,我将它精确地追踪到这条线。一旦删除路由,然后再次按预期工作。我只能假设这会导致某些 WebApi 依赖项将不正确的类型加载到无法解析路由的内存中 table.