代码之家  ›  专栏  ›  技术社区  ›  Mr. Bellis

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

  •  0
  • Mr. Bellis  · 技术社区  · 7 年前

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

    全球.asax

    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        GlobalConfiguration.Configuration.UseStructureMap<MasterRegistry>();
    
        var allDirectRoutes = WebApiConfig.GlobalObservableDirectRouteProvider.DirectRoutes;
    }
    

    WebApi。配置-我们在默认路由之前声明了MapHttpAttribute。

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

    控制器-在POST操作中返回CreatedAtRoute 这是由于找不到命名路由而引发错误的地方。

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

    注意:在WebApi中。配置我已经创建了一个ObservableDirectRouteProvider,它允许我查看启动时创建的路由,并且我可以看到我的命名路由存在于集合中。 enter image description here

    2 回复  |  直到 7 年前
        1
  •  1
  •   Luqman    7 年前

    如果我们在控制器上使用路由前缀,我们应该为所有动作定义路由名称。使用此

    [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)
    
        2
  •  0
  •   Mr. Bellis    7 年前

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

    scanner.SingleImplementationsOfInterface();
    

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