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