Custom Route Constraints

You can create custom route constraints by implementing the IHttpRouteConstraint interface. For example, the following constraint restricts a parameter to a non-zero integer value.


public class NonZeroConstraint : 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)
{
long longValue;
if (value is long)
{
longValue = (long)value;
return longValue != 0;
} string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
if (Int64.TryParse(valueString, NumberStyles.Integer,
CultureInfo.InvariantCulture, out longValue))
{
return longValue != 0;
}
}
return false;
}
}

The following code shows how to register the constraint:


public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint)); config.MapHttpAttributeRoutes(constraintResolver);
}
}

Now you can apply the constraint in your routes:


[Route("{id:nonzero}")]
public HttpResponseMessage GetNonZero(int id) { ... }

You can also replace the entire DefaultInlineConstraintResolver class by implementing the IInlineConstraintResolver interface. Doing so will replace all of the built-in constraints, unless your implementation of IInlineConstraintResolver specifically adds them.

最新文章

  1. 关于“线程间操作无效: 从不是创建控件’textBox1‘的线程访问它”异常的解决方法
  2. ASP.NET 5 入门(1) - 建立和开发ASP.NET 5 项目
  3. 创建下拉列表并通过ajax填充下拉数据
  4. wall
  5. libthrift0.9.0解析(二)之TSimpleServer
  6. Python一路走来 - 模块
  7. 多目标遗传算法 ------ NSGA-II (部分源码解析)介绍
  8. springboot2 webflux 响应式编程学习路径
  9. read()和write()
  10. 初探设计模式5:Spring涉及到的9种设计模式
  11. 如何去掉wordpress网站url里面的index.php(Apache服务器)
  12. Sliverlight调用WebService跨域问题解决
  13. Entity Framework 6 自定义连接字符串ConnectionString连接MySQL
  14. Java相关框架资料及其基础资料、进阶资料、测试资料之分享
  15. 【转载】JS Number类型数字位数及IEEE754标准
  16. Django 2.0 学习(18):Django 缓存、信号和extra
  17. JS日历控件特效代码layDate
  18. 从零开始完整搭建 Spring-Boot 项目开发框架的教程
  19. Java-Runoob:Java switch case
  20. R语言学习笔记(十):零碎知识点(21-25)

热门文章

  1. redis的持久化 rdb和aof
  2. Python3 md5加密
  3. 将图片转换为base64 格式
  4. CodeForces 689E Mike and Geometry Problem
  5. XTU 1246 Heartstone
  6. Java的URL来下载网页源码
  7. mysql 时间类型分类
  8. HTML5 &lt;meta&gt; 标签属性
  9. sap 设备cnsapwin不支持页格式*****
  10. CNN计算过程