C# webapi:一个名为';X';在路由集合中找不到

C# webapi:一个名为';X';在路由集合中找不到,c#,asp.net-web-api,asp.net-web-api-routing,C#,Asp.net Web Api,Asp.net Web Api Routing,我已经尝试了Stackoverflow和internet上其他地方关于此错误的所有解决方案,但我们仍然遇到了问题 所以我们有一个.NETAPI,它有一个POST方法,然后返回一个CreatedAtRoute响应(201)。问题是,当返回CreatedAtRoute响应时,我们得到错误“在路由集合中找不到名为“X”的路由”,其中X是我们的路由的名称 Global.asax protected void Application_Start() { GlobalConfiguration.Co

我已经尝试了Stackoverflow和internet上其他地方关于此错误的所有解决方案,但我们仍然遇到了问题

所以我们有一个.NETAPI,它有一个POST方法,然后返回一个CreatedAtRoute响应(201)。问题是,当返回CreatedAtRoute响应时,我们得到错误“在路由集合中找不到名为“X”的路由”,其中X是我们的路由的名称

Global.asax

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

    var allDirectRoutes = WebApiConfig.GlobalObservableDirectRouteProvider.DirectRoutes;
}
控制器-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);
}
注意:在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)
[HttpGet]
[路由(Name=“GetComponents”)]
[SwaggerResponse(HttpStatusCode.OK,Type=typeof(IEnumerable))]
公共异步任务Get(int page=0,int pageSize=CoreModels.Pagination.DefaultPageSize)

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

在StructureMap注册表中,我们正在调用

scanner.SingleImplementationsOfInterface();

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

请包含
公共异步任务Get(Guid id)
方法的全部内容。添加了完整Get(id)方法code@Mr.Bellis路由正在使用无效的路由约束
[Route(“{id:guid}”,Name=“GetCompoundById”)]
//注意小写的guidNkosi-我已经尝试了使用大写和小写的guid约束,两个版本都没有任何区别。我仍然看到System.Web.Http.HttpRouteCollection.GetVirtualPath出现异常。这并没有解决问题,我们已经在使用命名路由,问题是在使用“CreatedAtRoute”响应时找不到命名路由。
[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)
scanner.SingleImplementationsOfInterface();