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

Routing for executing different GET methods with same type of parameter

有人可以帮我做路由吗?

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)

我为第一个请求执行 public IHttpActionResult Get(Guid uid) 方法要解决什么问题?

您正在混合使用基于约定的路由和属性路由。 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){...}
}