WebApi 2使用属性路由构建嵌套路由.结果同时映射到两个控制器

WebApi 2使用属性路由构建嵌套路由.结果同时映射到两个控制器

问题描述:

我有两个控制器,一个名为产品",另一个名为"ProductsGroup"

I have two controllers one named "Products" and the other "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);
    }
}

当我这样路由ProductGroupsController时,由于发现与URL匹配的多个控制器类型",我无法访问

When i route like this the ProductGroupsController i not accessable due to "Multiple controller types were found that match the URL"

是否可以使路由忽略url的产品"部分,而仅映射到productgroupscontroller?

Is it possible to make the routing ignore the "products" part of the url and only map to the productgroupscontroller?

请考虑同时使用单个控制器:

Consider using single controller for both:

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

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

或者不要使用RoutePrefixes:

Or don't use RoutePrefixes:

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

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