用于执行具有相同类型参数的不同GET方法的路由

时间:2016-10-18 13:58:33

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

有人可以帮我解决路由问题吗?

WebApiConfig 中,我有这个映射

config.Routes.MapHttpRoute(DefaultApi",
    routeTemplate: "{controller}/{uid}",
    defaults: new {uid = RouteParameter.Optional}
);

和控制器中的两个方法

[RoutePrefix("AppartmentCategory")]
public class AppartmentCategoryController : ApiController
{
    [HttpGet]
    public IHttpActionResult Get(Guid uid){...}

    [HttpGet]
    [Route("{propertyUid?}")]
    public IHttpActionResult GetList(Guid propertyUid){...}
}

当我尝试发送请求时

1. http://.../AppartmentCategory/043F61D1-7194-E611-A98B-9C5C8E0005FA

2. http://.../AppartmentCategory/?propertyUid=2fdc968d-0192-e611-a98b-9c5c8e0005fa

在两种情况下执行方法 public IHttpActionResult GetList(Guid propertyUid)

我为第一次请求执行公共IHttpActionResult Get(Guid uid)方法的原因是什么?

1 个答案:

答案 0 :(得分:1)

您正在混合基于约定的路由和属性路由。 config.MapHttpAttributeRoutes()在基于约定的路由之前映射(应该如此)

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(DefaultApi",
    routeTemplate: "{controller}/{uid}",
    defaults: new {uid = RouteParameter.Optional}
);

所以它会首先击中GetLists,因为第一场比赛总是在匹配模板时获胜。从技术上讲,两种行为都有类似的路线。

[RoutePrefix("AppartmentCategory")]
public class AppartmentCategoryController : ApiController
{
    //GET AppartmentCategory/043F61D1-7194-E611-A98B-9C5C8E0005FA VIA CONVENTION-BASED ROUTING
    [HttpGet]
    public IHttpActionResult Get(Guid uid){...}

    //GET AppartmentCategory/2fdc968d-0192-e611-a98b-9c5c8e0005fa VIA ATTRIBUTE ROUTING    
    [HttpGet]
    [Route("{propertyUid?}")]
    public IHttpActionResult GetList(Guid propertyUid){...}
}

您应该尝试稍微区分这两个操作,并尝试不在同一个控制器中混合使用基于约定的路由。

[RoutePrefix("AppartmentCategory")]
public class AppartmentCategoryController : ApiController {
    //GET AppartmentCategory/043F61D1-7194-E611-A98B-9C5C8E0005FA
    [HttpGet]
    [Route("{uid:guid}")]
    public IHttpActionResult Get(Guid uid){...}

    //GET AppartmentCategory?propertyUid=2fdc968d-0192-e611-a98b-9c5c8e0005fa
    [HttpGet]
    [Route("")]
    public IHttpActionResult GetList(Guid propertyUid){...}
}