ASP.NET MVC 5.1 开始已经支持基于特性的路由(http://attributerouting.net),ASP.NET WEB API 2 同时也支持了这一特性。

启用特性路

由只需要在webapiconfig设置

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableSystemDiagnosticsTracing();
// Web API routes[设置特性路由]
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

使用RoutePrefix特性

[RoutePrefix("orders")]
public class OrdersController : ApiController
{
[Route("{id}")]
public Order Get(int id) { }
[Route("{id}/approve")]
public Order Approve(int id) { }
}

使用特性路由可以更简洁的定义你的URL(RoutePrefix特性定义的前缀还可以带参数变量)

public class MoviesController : ApiController
{
[Route("movies")]
public IEnumerable<Movie> Get() { }
[Route("actors/{actorId}/movies")]
public IEnumerable<Movie> GetByActor(int actorId) { }
[Route("directors/{directorId}/movies")]
public IEnumerable<Movie> GetByDirector(int directorId) { }
}

特性路由同时提供了一些基于参数约定,默认值等设置

//Optional parameter
[Route("people/{name?}")]
//Default value
[Route("people/{name=Dan}")]
//Constraint: Alphabetic characters only.
[Route("people/{name:alpha}")]

路由约束

可以通过"{参数变量名称:约束}"来约束路由中的参数变量

[Route("users/{id:int}"]
public User GetUserById(int id) { ... } [Route("users/{name}"]
public User GetUserByName(string name) { ... }

可选参数及其默认值

[Route("api/{id:int?}")]
public IEnumerable<T> Get(int id = 8){}

ASP.NET Web API内置约束包括

{x:alpha} 约束大小写英文字母
{x:bool}
{x:datetime}
{x:decimal}
{x:double}
{x:float}
{x:guid}
{x:int}
{x:length(6)}
{x:length(1,20)} 约束长度范围
{x:long}
{x:maxlength(10)}
{x:min(10)}
{x:range(10,50)}
{x:regex(正则表达式)}

可以为一个参数变量同时设置多个约束

[Route("api/{id:int:min(1)}")]

自定义约束

实现IHttpRouteConstraint接口,可自定义约束规则。实现一个不能为0的约束

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;
}
}

在WebApiConfig中注册自定义约束

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

使用自定义约束

[Route("{id:nonzero}")]

Refer:

Attribute Routing in Web API 2

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

What's New in ASP.NET Web API 2.1

http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21

visual-studio-2013 overview

http://www.asp.net/visual-studio/overview/2013/release-notes

ASP.NET Web API 2 中的特性路由的更多相关文章

  1. ASP.NET Web API 2 中的属性路由使用(转载)

    转载地址:ASP.NET Web API 2 中的属性路由使用

  2. ASP.NET Web API 2中的属性路由(Attribute Routing)

    如何启用属性路由并描述属性路由的各种选项? Why Attribute Routing? Web API的第一个版本使用基于约定的路由.在这种类型的路由中,您可以定义一个或多个路由模板,这些模板基本上 ...

  3. ASP.NET Web API 2.0新特性:Attribute Routing1

    ASP.NET Web API 2.0新特性:Attribute Routing[上篇] 对于一个针对ASP.NET Web API的调用请求来说,请求的URL和对应的HTTP方法的组合最终决定了目标 ...

  4. 【ASP.NET Web API教程】4.2 路由与动作选择

    原文:[ASP.NET Web API教程]4.2 路由与动作选择 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. 4.2 Routing ...

  5. Web API 2中的属性路由

    Web API 2中的属性路由 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.ht ...

  6. 在ASP.NET Web API项目中使用Hangfire实现后台任务处理

    当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送.由于推送这个具体功能,我们采用了第三方的服务.而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现 ...

  7. Asp.Net Web API 2第八课——Web API 2中的属性路由

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 路由就是Web API如何 ...

  8. ASP.NET Web API 2中的错误处理

    前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...

  9. [翻译]ASP.NET Web API 2 中的全局错误处理

    目录 已存在的选项 解决方案预览 设计原则 什么时候去用 方案详情 示例 附录: 基类详情 原文链接 Global Error Handling in ASP.NET Web API 2 由于翻译水平 ...

随机推荐

  1. Egret 摇一摇功能

    一  什么是重力感应 二 什么是陀螺仪 三 Egret中的摇一摇是利用什么原理实现的 四 摇一摇代码 一 什么是重力感应 二 什么是陀螺仪 三 Egret中的摇一摇是利用什么原理实现的 大概是利用手机 ...

  2. session基础

    1.每个页面都必须开启session_start()后才能在每个页面里面使用session. 2.session_start()初始化session,第一次访问会生成一个唯一会话ID保存在客户端(是基 ...

  3. CSS 概念 Block Inline Containing block

    Block 元素 包括 "block-level box," "block container box," and "block box" ...

  4. VC++ 控制外部程序,向外部程序发送一个消息的方法

    这里需要考虑两部分的内容: 发送端: 查找对应的窗体,找到CWnd的值 向窗体发送消息 举例: CWnd* wnd = FindWindow(NULL, _T("选择题做题过程中" ...

  5. js 构造函数

    //构造函数  //使自己的对象多次复制,同时实例根据设置的访问等级可以访问其内部的属性和方法  //当对象被实例化后,构造函数会立即执行它所包含的任何代码  function myObject(ms ...

  6. python 循环定时器

    有时候需要循环执行某个任务,最简单的就是用thread.Timer. 谷歌了一下,发现大家竟然用sleep 来实现循环,也不知道谁想的这个方法,竟然很少有人想到join一下,很奇怪. # -*- co ...

  7. [其他] 蒙特卡洛(Monte Carlo)模拟手把手教基于EXCEL与Crystal Ball的蒙特卡洛成本模拟过程实例:

    http://www.cqt8.com/soft/html/723.html下载,官网下载 (转帖)1.定义: 蒙特卡洛(Monte Carlo)模拟是一种通过设定随机过程,反复生成时间序列,计算参数 ...

  8. linux运维笔记——常用命令详解diff

    1.diff 你可以把diff看成是linux上的文件比对工具 例子文件内容: [root@localhost disks]# cat test1.txt a b c d [root@localhos ...

  9. js 运算符优先级

    在看jquery源码,仔细看入口函数的时候,有点懵了.看到与或.多重三目,傻傻的分不清,就代码仔细的区分下运算符优先级,以前都是呼呼的飘过.看来任何一个细节都不能忽略,不然效率极低.. !functi ...

  10. 最新做路径动画必备Simple Waypoint System5.1.1最新做路径动画必备Simple Waypoint System5.1.1

    NEW IN 5.0: up to 400% faster thanks to the DOTween engine! UnityEvents, new movement options and mo ...