WebApi 2使用属性路由构建嵌套路由.导致同时映射到两个控制器
本文关键字:路由 映射 控制器 两个 属性 构建 WebApi 嵌套 | 更新日期: 2023-09-27 18:21:59
我有两个控制器,一个命名为"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);
}
}
当我像这样路由ProductGroupsController时,由于"发现多个控制器类型与URL匹配",我无法访问它
是否可以让路由忽略url中的"products"部分,只映射到productgroupscontroller?
考虑同时使用单个控制器:
[RoutePrefix("api/{clientUrl}/products")]
public class ProductsController : BaseApiController
{
[Route("")]
public HttpResponseMessage GetProducts() {}
[Route("groups")]
public HttpResponseMessage GetProductGroups() {}
}
或者不使用RoutePrefixs:
public class ProductsController : BaseApiController
{
[Route("api/{clientUrl}/products")]
public HttpResponseMessage Get() {}
}
public class ProductGroupsController : BaseApiController
{
[Route("api/{clientUrl}/products/groups")]
public HttpResponseMessage Get() { }
}