WebApi 2 Building nested route using attribute routing. Results in mapping to two controllers at the same time

心已入冬 提交于 2019-12-13 15:42:31

问题


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

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

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


回答1:


Consider using single controller for both:

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

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

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()    {  }
}


来源:https://stackoverflow.com/questions/25870412/webapi-2-building-nested-route-using-attribute-routing-results-in-mapping-to-tw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!