WebApi 2使用属性路由构建嵌套路由.结果同时映射到两个控制器 [英] WebApi 2 Building nested route using attribute routing. Results in mapping to two controllers at the same time

查看:78
本文介绍了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()    {  }
}

这篇关于WebApi 2使用属性路由构建嵌套路由.结果同时映射到两个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆