时间紧迫,考虑这种如下两组Api
//水果蔬菜 api/fruit/good/12 api/vegetable/good/12 //日用品和电器 api/commodity/good/12 api/electric/good/12
以上两组请求我们希望分别由两个action执行,api/{type}/good/{id} ,路由结构相同,势必会导致路由冲突。下面我们引入IHttpRouteConstraint来解决这个问题
public class FruitAndVegetableTypeConstriant : IHttpRouteConstraint { public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) { object value; if (values.TryGetValue(parameterName, out value) && value != null) { string topicType = value.ToString().ToLower(); return topicType.Equals("fruit", StringComparison.Ordinal) || topicType.Equals("vegetable", StringComparison.Ordinal); } return false; } }
在路由注册的地方加入一下代码,注入内连解析器,代码如下:
var constraintResolver = new DefaultInlineConstraintResolver(); constraintResolver.ConstraintMap.Add("fruitAndVegetable", typeof(FruitAndVegetableTypeConstriant)); config.MapHttpAttributeRoutes(constraintResolver);
//config.MapHttpAttributeRoutes();
Action路由配置如下:
[Route("{goodType:fruitAndVegetable}/good/{id}")] public IHttpActionResult GetGoods(string goodType, int id) { return Ok(); } [Route("{goodType}/good/{id}")] public IHttpActionResult GetOtherGoods(string goodType, int id) { return Ok(); }
这样我就完成了,fruit And Vegetable 走第一条api,其他类型走第二条api。当然其实IHttpRouteConstraint的主要作用是做路由过滤。