博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
webapi中的自定义路由约束
阅读量:4680 次
发布时间:2019-06-09

本文共 1593 字,大约阅读时间需要 5 分钟。

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
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.

转载于:https://www.cnblogs.com/a14907/p/5099445.html

你可能感兴趣的文章
C# 和 c++的语法不同点
查看>>
jquery blockUI 扩展插件 Dialog
查看>>
第一次去CSDN听课感受
查看>>
iOS开发UI篇—实现一个私人通讯录小应用(二)
查看>>
iOS开发UI篇—UITableview控件使用小结
查看>>
lesson1 预备知识
查看>>
Copy code from eclipse to word, save syntax.
查看>>
arguments.callee的作用及替换方案
查看>>
23 Java学习之RandomAccessFile
查看>>
SSH远程会话管理工具 - screen使用教程
查看>>
[翻译]WPF控件库 MaterialDesignInXamlToolkit (1)
查看>>
hibernate validation HV000030: No validator could be found for constraint
查看>>
前端优化
查看>>
bzoj1511 [POI2006]OKR-Periods of Words kmp+乱搞
查看>>
心语4
查看>>
Telink MESH SDK 如何使用PWM
查看>>
LR SP PC
查看>>
C# 图片识别(支持21种语言)【转】
查看>>
C# 循环语句 for
查看>>
jQuery基础教程
查看>>