WebApi 2使用属性路由构建嵌套路由。导致同时映射到两个控制器

时间:2014-09-16 13:41:38

标签: c# asp.net-web-api asp.net-web-api-routing

我有两个控制器,一个名为“Products”,另一个名为“ProductsGroup”

[RoutePrefix("api/{clientUrl}/products")]
public class ProductsController : BaseApiController
{
    /// <summary>
    /// Get all products from a client
    /// </summary>
    /// <returns></returns>
    [Route("")]
    public HttpResponseMessage Get()
    {
        var model = Repository.GetProducts(ClientId).Select(p => ModelFactory.Create<ProductsModel>(p));
        return Request.CreateResponse(HttpStatusCode.OK, model);
    }
}

[RoutePrefix("api/{clientUrl}/products/groups")]
public class ProductGroupsController : BaseApiController
{
    /// <summary>
    /// Get all productgroups
    /// </summary>
    /// <returns></returns>
    [Route("")]
    public HttpResponseMessage Get()
    {
        var model = Repository.GetProductGroups(ClientId);
        return Request.CreateResponse(HttpStatusCode.OK, model);
    }
}

当我像这样路由时,由于“找到了与URL匹配的多个控制器类型”,我无法访问ProductGroupsController

是否可以使路由忽略url的“products”部分并仅映射到productgroupscontroller?

1 个答案:

答案 0 :(得分:5)

考虑使用单一控制器:

[RoutePrefix("api/{clientUrl}/products")]
public class ProductsController : BaseApiController
{
    [Route("")]
    public HttpResponseMessage GetProducts()  {}

    [Route("groups")]
    public HttpResponseMessage GetProductGroups()  {}
}

或者不要使用RoutePrefixes:

public class ProductsController : BaseApiController
{
    [Route("api/{clientUrl}/products")]
    public HttpResponseMessage Get()  {}
}

public class ProductGroupsController : BaseApiController
{
    [Route("api/{clientUrl}/products/groups")]
    public HttpResponseMessage Get()    {  }
}